我有一个字符串“abcabc”,我想分割它并像这样打印:
abc
abc
字符串的代码定义:
String word = "abcabc";
最佳答案
我们可以尝试使用 String#replaceAll
作为单行选项:
String input = "abcabc";
String output = input.replaceAll("^(.*)(?=\\1$).*", "$1\n$1");
System.out.println(output);
打印:
abc
abc
这个想法是将一个模式应用于整个字符串,匹配并捕获一些数量,然后在末尾添加相同的数量。以下是针对您的确切输入 abcabc
执行的模式解释:
(.*) match 'abc'
(?=\1$) then lookahead and assert that what follows to the end of the string
is exactly another 'abc'
.* consume, but do not match, the remainder of the input (which must be 'abc')
然后,我们替换为 $1\n$1
,这是第一个捕获组两次,以换行符分隔。
关于java - 将字符串拆分为 2 个相同的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59998253/