splitting a string into N number of strings [closed]
I want to split a string into N number of 2char strings. I know I must use String.subSequence. However I want it to keep creating these until the string is > 2
Try this:
int n = 3;
String s = "abcdefghijkl";
System.out.println(Arrays.toString( s.split("(?<=\\G.{2})(?=.)", n + 1 ) ) );
//prints: [ab, cd, ef, ghijkl], i.e. you have 3 2-char groups and the rest
The regex works as follows: find any position after 2 characters (zero-width postive look behind (?<=...)
) starting from the last match position (\G
) and before at least one more character (zero-width positive look ahead (?=.)
). This should not match the positions at the start and end of the string and thus n can be as big as you want without resulting in an empty string at the start or the end.
Edit: if you want to split as much as possible, just leave out the second parameter to split.
Example:
String digits = "123456789";
System.out.println(Arrays.toString( digits.split("(?<=\\G.{2})(?=.)" ) ) ); //no second parameter
//prints: [12, 34, 56, 78, 9]
String s = "asdasdasd";
List<String> segments = new ArrayList<String>();
for (int i = 1; i < s.length(); i=i+2) {
segments.add(s.substring(i-1, i+1));
}
System.out.println(segments.toString());
精彩评论