Java 将字符串拆分为两个相同的单词
我有一个字符串“abcabc”,我想将其拆分并按如下方式打印:Java 将字符串拆分为两个相同的单词,java,split,Java,Split,我有一个字符串“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 其思想是对整个
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
,它是第一个捕获组,两次使用换行符分隔。字符串拆分():
public class Split {
public static void main(String args[])
{
String str = "ABC@ABC";
String[] arrOfStr = str.split("@", 5);
for (String a : arrOfStr)
System.out.println(a);
}
}
这还打印:
ABC
ABC
类堆栈{
公共静态void main(字符串$[]){
foo();
}
公共静态void foo(){
字符串in=“abc”//空格用作分隔符。
String res[]=in.split(“”;//返回字符串数组
对于(int i=0;i使用Pattern
和Matcher
的组合,您可以提供更多的细节,如-您知道有多少重复吗?是否总是有完整的重复?是否有其他字符?如果您能更详细地解释正则表达式(“^(.*)(?=\\1$)*,“$1\n$1”)
,或者[String[]array=word.split(“(?阅读问题。用String.split方法更新答案。你的答案只打印abc两次。他想拆分字符串并打印。@MarkNiles,输入字符串不正确。”ABC@ABC但它是ABCABC
class Stack{
public static void main(String $[]){
foo();
}
public static void foo(){
String in="abc abc abc";//spaces are used as seperator.
String res[]=in.split(" ");//Returns an Array of String
for(int i=0;i<res.length;i++)
System.out.println(res[i]);
}
}
output:
abc
abc
abc