开发者

splitting a string into N number of strings [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an e开发者_如何学Pythonxtraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center. Closed 11 years ago.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜