简体   繁体   中英

Need to split the Java String into two arrays

I have a String of the following kind in Java. The idea is that the string will contain a list of numbers followed by'Y-' or 'N-'. They may be of any length. I need to extract the list of numbers into two, separately.

String str = "Y-1,2,3,4N-5,6,7,8" 
//Other examples: "Y-1N-3,6,5" or "Y-1,2,9,18N-36"

I need to break it down into the following arrays:

arr1[] = {1,2,3,4}
arr2[] = {5,6,7,8}

How do I do it?

First split the string into the two arrays string parts

    String str = "Y-1,2,3,4N-5,6,7,8";
    
    String str1 = str.substring(2, str.indexOf("N-")); // "1,2,3,4"
    String str2 = str.substring(str.indexOf("N-") + 2); // "5,6,7,8"

Then convert the array of strings to an array of ints using the Integer.parseInt() , simple java-8 solution with streams:

    int[] array1 = Arrays.stream(str1.split(",")).mapToInt(Integer::parseInt).toArray();
    int[] array2 = Arrays.stream(str2.split(",")).mapToInt(Integer::parseInt).toArray();

If you are in a version of java without streams, you need to use a simple for loop instead of the Arrays.stream()

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