英文:
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()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论