我试图以这种方式将字符串中的每个单词和/或数字/符号组合输入加倍:
My name is >> My My name name is is
148 !! 697 >> 148 148 !! !! 697 697
The code is 428 >> The The code code is is 428 428
我已经花了一段时间了,但我似乎不知道如何让加倍正常工作或使加倍部分彼此分开。
最佳答案
使用,a regular expression ,你可以很简单地做到这一点。以下groups所有非空白字符 (\S
) 并使用反向引用 $1
将其自身替换两次。
public static void main(String[] args) {
String[] str = { "My name is", "148 !! 697", "The code is 428" };
Pattern pattern = Pattern.compile("(\\S+)");
for (String s : str) {
String res = pattern.matcher(s).replaceAll("$1 $1");
System.out.println(res);
}
}
这会打印
My My name name is is
148 148 !! !! 697 697
The The code code is is 428 428
关于java - 将字符串中的每个单词或数字组合加倍,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36378195/