将一个字符串分割成N个字符串

发布于 2024-12-06 09:40:12 字数 84 浏览 0 评论 0原文

我想将一个字符串拆分为 N 个 2char 字符串。我知道我必须使用 String.subSequence。但是我希望它继续创建这些直到字符串> 2

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

狼性发作 2024-12-13 09:40:12

试试这个:

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

正则表达式的工作原理如下:从最后一个匹配位置 (\ G)并且在至少一个字符之前(零宽度正向前视 (?=.))。这不应与字符串开头和结尾的位置匹配,因此 n 可以任意大,而不会导致开头或结尾出现空字符串。

编辑:如果您想尽可能多地拆分,只需省略要拆分的第二个参数即可。

例子:

String digits = "123456789";

System.out.println(Arrays.toString( digits.split("(?<=\\G.{2})(?=.)" ) ) ); //no second parameter

//prints: [12, 34, 56, 78, 9]

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]
感情废物 2024-12-13 09:40:12
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());
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());
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文