简体   繁体   中英

Split String into to 2 same words

I have a String "abcabc" and I want to split it and print like this:

abc

abc

Code definition for string:

String word = "abcabc";

We can try using String#replaceAll for a one line option:

String input = "abcabc";
String output = input.replaceAll("^(.*)(?=\\1$).*", "$1\n$1");
System.out.println(output);

This prints:

abc
abc

The idea is to apply a pattern to the entire string which matches and captures some quantity, which is then followed by the same quantity to the end. Here is the pattern explained as executed against your exact input 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')

Then, we replace with $1\\n$1 , which is the first capture group twice, separated by a newline.

The string split():

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); 
} 
} 

This Also Prints :

ABC
ABC
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM