-5

I have a string that contains numbers and I would like to put this numbers in a int array.

The format is like this:

String s = "234, 1, 23, 345";

int[] values;

What i want:

values[0]=234

values[1]=1

values[2]=23

values[3]=345
Patrick Kostjens
  • 5,065
  • 6
  • 29
  • 46
  • http://stackoverflow.com/questions/3481828/how-to-split-a-string-in-java read this and try yourself – Pons Mar 16 '17 at 20:14
  • 3
    Step one: [Split the string into an array.](http://stackoverflow.com/q/3481828/1828486). Step 2: [Parse the strings and move to a new array.](http://stackoverflow.com/q/5585779/1828486) – Mage Xy Mar 16 '17 at 20:15
  • Same class as [How to convert a string array to an int array](http://stackoverflow.com/q/42842961/205233)? – Filburt Mar 16 '17 at 20:15
  • `int[] values = Pattern.compile(", ").splitAsStream(s).mapToInt(Integer::parseInt).toArray();` – shmosel Mar 16 '17 at 20:27

5 Answers5

2

You can split the string by comma, iterate through tokens and add them into another array by converting each token into integer, e.g.:

public static void main(String[] args){
    String s = "234, 1, 23, 345";
    String[] tokens = s.split(",");
    int[] numbers = new int[tokens.length];
    for(int i=0 ; i<tokens.length ; i++){
        numbers[i] = Integer.parseInt(tokens[i].trim());
    }
}
Darshan Mehta
  • 30,102
  • 11
  • 68
  • 102
0

Using Java8 :

String s = "234, 1, 23, 345";
String array[] = s.split(", ");
Stream.of(array).mapToInt(Integer::parseInt).toArray();
Shiladittya Chakraborty
  • 4,270
  • 8
  • 45
  • 94
0

Try splitting the String

String s = "234, 1, 23, 345";
String array[] = s.split(", ");
int a[] = new int[array.length];
for(int i=0;i<a.length;i++)
    a[i] = Integer.parseInt(array[i]);
dumbPotato21
  • 5,669
  • 5
  • 21
  • 34
0

Look into using a String utility

String[] strings= s.split(","); 

and then loop over strings and add them to the int array using something like this

for(int i = 0; i < strings.size(); i++){
    values [i] = Integer.parseInt(strings[i]);
}
0

You should Split, for-loop, and parse to int

String s = "234, 1, 23, 345";
String[] splittedS = s.split(", ");
int[] values = new int[splittedS.length];

for (int i = 0; i < splittedS.length; i++) {
    values[i] = Integer.parseInt(splittedS[i]);
}
System.out.println(Arrays.toString(values));

and if you are able to use streams java8

String[] inputStringArray = s.split(", ");
Integer[] convertedREsult = Arrays.stream(inputStringArray).map(Integer::parseInt).toArray(Integer[]::new);
System.out.println(Arrays.toString(convertedREsult));
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97