需要将Java字符串分成两个数组。

huangapple go评论77阅读模式
英文:

Need to split the Java String into two arrays

问题

我有一个类似以下的Java字符串。想法是字符串将包含一个数字列表,后面跟着'Y-'或'N-'。它们可以是任意长度。我需要将数字列表分别提取出来。

String str = "Y-1,2,3,4N-5,6,7,8"
//其他示例: "Y-1N-3,6,5" 或 "Y-1,2,9,18N-36"

我需要将其拆分为以下数组:

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

我该如何做呢?

英文:

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?

答案1

得分: 1

首先将字符串拆分为两个字符串数组部分

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"

然后使用Integer.parseInt()将字符串数组转换为整数数组,使用Java 8中的流进行简单的解决方案:

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

如果您的Java版本不支持流操作,需要使用简单的for循环来替代Arrays.stream()

英文:

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()

huangapple
  • 本文由 发表于 2020年8月9日 00:20:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/63317664.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定