简体   繁体   中英

How to convert a string array to an int array?

How do I convert a string like:

"114 214 219"

Into an an int array so I have something like this stored in my int array:

int[] couseNumbers = int[3];

for(int i = 0; i < 3; i++){
     courseNumbers[i] = Integer.parseInt(/*get int in the string array*/);
}

Split the String into an array first.

String[] stringArray = "114 214 219".split(" ");

Then in the loop you can access that array:

courseNumbers[i] = Integer.parseInt(stringArray[i])

Try this

String s = "1 2 3";
String array[] = s.split(" "); //Splits the Array by spaces
int a[] = new int[array.length]; //Makes new int array
for(int i=0;i<a.length;i++){
    a[i] = Integer.parseInt(array[i]); //Converts String to int
}

Using Java 8 streams.

 List<Integer> courseNumbers = Arrays.stream("1123 213 23"
  .split(" ")).map(x-> Integer.parseInt(x))
  .collect(Collectors.toList());

Answer above by Eduardo Dennis will not work as string cannot convert to int directly. You can do something like this.

 public static void main(String []args){
    String s = "114 214 219";
    String [] courseNumbers = s.split(" ");
    Integer [] intArray = new Integer[courseNumbers.length];
    for(int i= 0; i < courseNumbers.length; i++){
        intArray[i] = Integer.parseInt(courseNumbers[i]);
    }

 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM