Sajid
Sajid

Reputation: 67

Convert a String containing space separated numbers into an integer array

If I have a String,

String x = "10 20 30 40";

Is there any way to convert it into an int array like this?

int[] y = {10, 20, 30, 40};

Upvotes: 2

Views: 4224

Answers (4)

Shantanu Deshpande
Shantanu Deshpande

Reputation: 224

int[] convert(String x){
     String[] val = x.split(" ");
     int[] arr = new int[val.length];
     for (int i = 0; i < val.length; ++i){
          arr[i] = Integer.parseInt(val[i]);
     }
     return arr;
}

Upvotes: 3

You can combine the functions like the c++

find(character,range)

and

substring(initial position,range)

and a counter to increment the initial position

to create a vector with the elements as srting

and finally parse all the elements to the int type

(i didn know how to do that in java)

Upvotes: -4

MRK187
MRK187

Reputation: 1595

Maybe something like this, to get you started with your assignment :)? Using Strings split method with regular expressions.

String x = "10 20 30 40";
String[] cut = x.split(" ");

Now you have an array in cut. Then you'll need to loop through that and get the Integer value of the Strings, and do whatever more you need to..

happy coding!

Upvotes: -2

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382112

In a functional way, using Java 8 streams:

int[] y = Arrays.stream(x.split(" ")).mapToInt(Integer::parseInt).toArray();

Upvotes: 8

Related Questions