Sergey Shustikov
Sergey Shustikov

Reputation: 15821

Java how to parse integers with spaces

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.

Upvotes: 1

Views: 3177

Answers (4)

Evan Knowles
Evan Knowles

Reputation: 7501

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

Upvotes: 11

Basim Khajwal
Basim Khajwal

Reputation: 936

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

Upvotes: 0

Rod_Algonquin
Rod_Algonquin

Reputation: 26198

String split[] = string.split(" ")

is will generate an array of string then you can parse the array to int.

Upvotes: 1

Rahul
Rahul

Reputation: 45060

  1. Split the String, using the String#split() method with the delimiter space.
  2. For each element in the String[], parse it into an int using Integer.parseInt() and add them to your int[].

Upvotes: 1

Related Questions