0

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.

1
  • 2
    String.split it does not work for an int so you would want to do maybe String[] nums = x.split("\\s+"); Im assuming x is the String of nums divided up by spaces? Look at @Juned Ashan answer Commented Oct 20, 2015 at 23:36

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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);
}

5 Comments

str is an int. How would your solution ever return something other than new String[] {String.valueOf(str)}?
@brimborium String.valueOf() will return the String for the int and split will return the String array ....
If you are converting an int to String, there is nothing to split, because it's just a single integer, there will never be a space...
@brimborium I believe questioner has got a string which he/she tried to convert to int using this int t = Integer.parseInt(x);
Thanks, the edit of your answer is much better. The first code segment (the one you initially posted) still does not make sense, because it is equal to what I wrote in my first comment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.