Search code examples
javastringsplitspecial-characters

How can i split string in java using combine special characters


How can I split a String using combine special characters?

For example, if the combine Special characters is {@}:

String str = "This is test string1.{@}This is test string2@(#*$ ((@@{}";
StringTokenizer stoken = new StringTokenizer(str, "\\{\\@\\}");
while (stoken.hasMoreElements()) {
    System.out.println(stoken.nextElement());
}

What I expect from above program is :

This is test string1.
This is test string2@(#*$ ((@@{}

Solution

  • You can not use characters with special meanings like : \ ^ $ . | ? * + ( ) [ { }, i think there are 12 of them. therefore change your character to split the string to something like "/-/"

    the code to do so looks like the one underneath:

    public class SplitString {
    
    public static void main(String[] args) {
    
        String s = "This is test string1./This is test string2@(#*$ ((@@{}";
        String[] fragments = s.split("/");
        String fragment1 = fragments[0];
        String fragment2 = fragments[1];
    
        System.out.println(fragment1);
        System.out.println(fragment2);
    
        }
    
    }
    

    this solution is based on the answer in this thread: Stackoverflow Split String