How exactly do I separate a single grouping of numbers in Java in a string of digits that contains more than 1 or 2 digits? For example, I need to only separate the digits in the groups larger than 1 or 2 digits in this string: 12,10,12914,10,641,10,11,11,2,10.
Also, how can I separate/split certain elements in an array in Java without separating all of the elements? For example, I need to separate the letters from the numbers, and separate the 12 from the 9, and the 6 from the 4 in this set of elements: [12a, 129, 14a, 64, 1a, 11b, 2a].
Thanks for any help!
CodePudding user response:
You could split the string since they are comma separate and then loop through each of the numbers and separate only those that meet your criteria.
String str = "12,10,12914,10,641,10,11,11,2,10";
str[] ary = str.split(",");
for (str s : ary) {
if ( s.length() > 1 ) {
//separate the contents of the string as you want
}
}
CodePudding user response:
You can do it like this.
In the first case:
- split the string on
,
possibly surrounded by white space. - filter strings > length of 2
- convert to an Integer and store in a list.
String s1 = "12,10,12914,10,641,10,11,11,2,10";
List<Integer> list1 = Arrays.stream(s1.split("\\s*,\\s*"))
.filter(str -> str.length() > 2).map(Integer::valueOf)
.toList();
System.out.println(list1);
Prints
[12914, 641]
In the second case
- split the same way as before.
- convert the string sans the last character (letter or digit) to an integer. This uses the
String.substring
method. - return in a list.
String s2 = "2a, 129, 14a, 64, 1a, 11b, 2a";
List<Integer> list2 = Arrays.stream(s2.split("\\s*,\\s*"))
.map(str -> Integer.valueOf(
str.substring(0, str.length() - 1)))
.toList();
System.out.println(list2);
Prints
[2, 12, 14, 6, 1, 11, 2]
In the second case an exception will be thrown if the items end in more than one non-digit character or are not at least 2 in length.
CodePudding user response:
If it helps you
public class Main
{
public static String example1(int[] in) {
String msg = "Example 1\n";
for(int idx=0; idx<in.length; idx ) {
msg = in[idx] ":";
String str=String.valueOf(in[idx]);
boolean split = false;
for(int i=1; i<str.length(); i ) {
char x = str.charAt(i-1);
char y = str.charAt(i);
if (x!=y && i == 1) {
msg = " " x;
}
if (x!=y) {
msg = " " y;
}
}
msg = "\n";
}
msg = "Done";
return msg;
}
public static void main(String[] args) {
int[] in = new int[] {12,10,12914,10,641,10,11,11,2,10};
String msg = example1(in);
System.out.println(msg);
}
}