I have a string, actually user put in console next string :
10 20 30 40 50
how i can parse it to int[] ?
I tried to use Integer.parseInt(String s); and parse string with String.indexOf(char c) but i think it's too awful solution.
You could use a Scanner and .nextInt(), or you could use the .split() command on the String to split it into an array of Strings and parse them separately.
For example:
Scanner scanner = new Scanner(yourString);
ArrayList<Integer> myInts = new ArrayList<Integer>();
while (scanner.hasNextInt()) {
myInts.add(scanner.nextInt());
}
For the split:
String[] intParts = yourString.split("\\s+");
ArrayList<Integer> myInts = new ArrayList<Integer>();
for (String intPart : intParts) {
myInts.add(Integer.parseInt(intPart));
}
Split the String, using the String#split() method with the delimiter space.
For each element in the String[], parse it into an int using Integer.parseInt() and add them to your int[].
String split[] = string.split(" ")
is will generate an array of string then you can parse the array to int.
Split the string then parse the integers like the following function:
int[] parseInts(String s){
String[] sNums = s.split(" ");
int[] nums = new int[sNums.length];
for(int i = 0; i < sNums.length; i++){
nums[i] = Integer.parseInt(sNums[i);
}
return nums;
}
Related
//convert the comma separated numeric string into the array of int.
public class HelloWorld
{
public static void main(String[] args)
{
// line is the input which have the comma separated number
String line = "1,2,3,1,2,2,1,2,3,";
// 1 > split
String[] inputNumber = line.split(",");
// 1.1 > declare int array
int number []= new int[10];
// 2 > convert the String into int and save it in int array.
for(int i=0; i<inputNumber.length;i++){
number[i]=Integer.parseInt(inputNumber[i]);
}
}
}
Is it their any better solution of doing it. please suggest or it is the only best solution of doing it.
My main aim of this question is to find the best solution.
Java 8 streams offer a nice and clean solution:
String line = "1,2,3,1,2,2,1,2,3,";
int[] numbers = Arrays.stream(line.split(",")).mapToInt(Integer::parseInt).toArray();
Edit: Since you asked for Java 7 - what you do is already pretty good, I changed just one detail. You should initialize the array with inputNumber.length so your code does not break if the input String changes.
Edit2: I also changed the naming a bit to make the code clearer.
String line = "1,2,3,1,2,2,1,2,3,";
String[] tokens = line.split(",");
int[] numbers = new int[tokens.length];
for (int i = 0; i < tokens.length; i++) {
numbers[i] = Integer.parseInt(tokens[i]);
}
By doing it in Java 7, you can get the String array first, then convert it to int array:
String[] tokens = line.split(",");
int[] nums = new int[tokens.length];
for(int x=0; x<tokens.length; x++)
nums[x] = Integer.parseInt(tokens[x]);
Since you don't like Java 8, here is the Best™ solution using some Guava utilities:
int[] numbers = Ints.toArray(
Lists.transform(
Splitter.on(',')
.omitEmptyStrings()
.splitToList("1,2,3,1,2,2,1,2,3,"),
Ints.stringConverter()));
How do I split a string with numbers?
Like if I have "20 40" entered, how do I split
it so I get 20, 40?
int t = Integer.parseInt(x);
int str = t;
String[] splited = str.split("\\s+");
My code.
If you're trying to parse a string that contains whitespace-delimited integer tokens, into an int array, the following will work:
String input = "20 40";
String[] tokens = input.split(" ");
int[] numbers = new int[tokens.length];
for (int i = 0; i < tokens.length; i++) {
numbers[i] = Integer.parseInt(tokens[i].trim());
}
You can also do this in a one-liner through the Iterables and Splitter utilities from the amazing Google Guava library:
Integer[] numbers = Iterables.toArray(Iterables.transform(
Splitter.on(' ').trimResults().split(input),
new Function<String, Integer>() {
#Override
public Integer apply(String token) {
return Integer.parseInt(token);
}
}), Integer.class);
You need to convert it to String value and then split, maybe like this:
String[] splited = String.valueOf(str).split("\\s+");
It seems you are reading the number as String and trying to convert it to integer before the split here:
int t = Integer.parseInt(x);
so you can actually split your variable x and get the indiviudal int values out of it like this:
String[] splited = x.split("\\s+");
for(String num:splited) {
int intVal = Integer.valueOf(num);
}
How do I create a method that takes a string as an argument, and returns the array whose elements are the words in the string.
This is what I have came up with so far:
// split takes some string as the argument, and returns the array
// whose elements are the words in the string
public static String[] split (String s)
{
// determine the number of words
java.util.Scanner t = new java.util.Scanner (s);
int countWords = 0;
String w;
while (t.hasNext ())
{
w = t.next ();
countWords++;
}
// create appropriate array and store the string’s words in it
// code here
}
As you can see, I can just input each word via Scanner. Now I just have to put all the words of the String into an array as the elements. However, I'm not sure how to proceed.
You can use StringTokenizer in java to devide your string into words:
StringTokenizer st = new StringTokenizer(str, " ");
And your output st whould be an array of words.
Take a look at this Java StringTokenizer tutorial for further information.
Your code whould look like:
StringTokenizer st = new StringTokenizer(s, " ");
int n=st.countTokens();
for(int i=0;i<n;i++) {
words[i]=st.nextToken();// words is your array of words
}
As Maroun Maroun commented, you should use the split(regex) method from Strings, but if you want to do this by yourself:
First, declare the array:
String[] words = new String[50]; // Since you are using an array you have to declare
// a fixed length.
// To avoid this, you can use an ArrayList
// (dynamic array) instead.
Then, you can fill the array inside the while loop:
while (t.hasNext()) {
w = t.next();
words[countWords] = w;
countWords++;
}
And finally return it:
return words;
Note:
The sentences
words[countWords] = w;
countWords++;
can be simplified in
words[countWords++] = w;
As #Maroun Maroun said: use the split function or like #chsdk said use StringTokenizer.
If you want to use scanner:
public static String[] split(String s)
{
Scanner sc = new Scanner(s);
ArrayList<String> l = new ArrayList<String>();
while(sc.hasNext())
{
l.add(sc.next());
}
String[] returnValue = new String[l.size()];
for(int i = 0; i < returnValue.length; ++i)
{
returnValue[i] = l.get(i);
}
return returnValue;
}
I am reading in a string, as an entire line of numbers, separated by spaces, ie ie 1 2 3 4 5. I want to convert them into an array of integers, so that I can manipulate them. But this code doesn't work. It says incompatible types.
String str = br.readLine();
int[] array = new int[4];
StringTokenizer tok = new StringTokenizer(str," ", true);
boolean expectDelim = false;
int i = 0;
while (tok.hasMoreTokens()) {
String token = tok.nextToken();
ar[i] = Integer.parseInt(token);
i++;
}
If you have a String s = "1 2 3 4 5" then you can split it into separate bits like this:
String[] bits = s.split(" ");
Now you have to put them into an int[] by converting each one:
int[] nums = new int[bits.length];
int i=0;
for (String s: bits)
nums[i++] = Integer.parseInt(s);
This will loop through each of the small strings in the split array, convert it to an integer, and put it into the new array.
You don't need the delimiters. Change this:
StringTokenizer tok = new StringTokenizer(str," ", true);
to this:
StringTokenizer tok = new StringTokenizer(str," ");
What's happening in your code is that it's trying to parse (space) as an int.
Alternatively, nowadays most people would just use String.split(...), as pointed out by chiastic-security.
You can use the following code to convert a String consisting of whitespace-separated numbers to an int[]:
import static java.util.Arrays.stream;
public class ConvertString {
public static void main(final String... args) {
final String s = "1 2 3 4 5";
final int[] numbers = stream(s.split("\\s+")).mapToInt(Integer::parseInt).toArray();
// Print it as a demo.
for (final int number : numbers)
System.out.format("%s ", number);
System.out.println();
}
}
Java 8 style solution:
String input = "1 2 3 4 5";
int[] numbers = Arrays.stream(input.split("\\s+"))
.mapToInt(Integer::parseInt).toArray();
I have a variable of type StringBuffer which has certain numbers in it say,
StringBuffer newString = new StringBuffer("25 75 25");
Now if I want to separate this out in an integer array, how could i do it?
for(int i=0;i<numberOfItemsInTheStore;i++){
newString.append(values.charAt(0));
values.deleteCharAt(0);
char c = values.charAt(0);
if(c==' ' || values.length()==1){
values.deleteCharAt(0);
value[i] = Integer.parseInt(newString.toString());
newString.delete(0, newString.length());
System.out.println(value[i]);
}
}
What might be wrong in the program?
String[] splits = newString.toString().split(" ");
int[] arrInt = new int[splits.length];
int idx = 0;
for (String s: splits){
arrInt[idx++] = Integer.parseInt(s);
}
You can get String array easily and when you want to use elements as int values use Integer.parseInt() method
StringBuffer newString = new StringBuffer("25 75 25");
String [] strArr = newString.toString().split(" ");
System.out.println(Arrays.toString(strArr));