Reputation: 67
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
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
Reputation: 134
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
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
Reputation: 382112
In a functional way, using Java 8 streams:
int[] y = Arrays.stream(x.split(" ")).mapToInt(Integer::parseInt).toArray();
Upvotes: 8