-1

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@(#*$ ((@@{}
J. Doe
  • 459
  • 4
  • 26
Beginner
  • 15
  • 3
  • I suggest you to google "java split string" – TDG Feb 06 '16 at 14:15
  • I'd suggest looking at the [indexOf(String, int)](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf%28java.lang.String,%20int%29) method for Strings. If you keep track of the current index in your Tokenizer object, you'll be able to find the index of the next instance of your special character string below, and return the substring leading to the special characters (provided by indexOf) in your nextElement method. – jsoberg Feb 06 '16 at 14:19

1 Answers1

0

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

Community
  • 1
  • 1
J. Doe
  • 459
  • 4
  • 26