[英]Need to split the Java String into two arrays
I have a String of the following kind in Java.我在 Java 中有以下类型的字符串。 The idea is that the string will contain a list of numbers followed by'Y-' or 'N-'.
这个想法是字符串将包含一个数字列表,后跟“Y-”或“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:我需要将其分解为以下 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首先将字符串拆分为两个 arrays 字符串部分
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:然后使用
Integer.parseInt()
将字符串数组转换为整数数组,简单的 java-8 解决方案与流:
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()
如果您使用的是没有流的 java 版本,则需要使用简单的 for 循环而不是
Arrays.stream()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.