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);
}
str is an int. How would your solution ever return something other than new String[] {String.valueOf(str)}?int to String, there is nothing to split, because it's just a single integer, there will never be a space...
String.splitit does not work for an int so you would want to do maybeString[] nums = x.split("\\s+");Im assumingxis theStringof nums divided up by spaces? Look at @Juned Ashan answer