Chit Khine
Chit Khine

Reputation: 850

How to split the string in java by \?

I would like to split the special character "\". However, it doesn't seem to work out using

a.split("\");

or

a.split("\\");

Upvotes: 4

Views: 3226

Answers (4)

Elliott Frisch
Elliott Frisch

Reputation: 201537

While you could escape the regular expression to String.split with the somewhat surprising

String str = "a\\b\\c";
str.split("\\\\");

it is also possible to compile a Pattern with Pattern.LITERAL and then use Pattern.split(CharSequence) like

String str = "a\\b\\c";
Pattern p = Pattern.compile("\\", Pattern.LITERAL);
String[] arr = p.split(str);
System.out.println(Arrays.toString(arr));

Which outputs

[a, b, c]

Upvotes: 5

user6308523
user6308523

Reputation:

 String s = "light\\hello\\text.txt";
    String s3[] = s.split(Pattern.quote("\\"));
    for (int i = 0; i < s3.length; i++) {
        System.out.println(i+" value "+s3[i]);
}

Upvotes: 0

user4696837
user4696837

Reputation:

Simply use \n inside the string where need. No method need to split.

  1. "\" special character in java. It is use to skip a character. Such as String s = "I am a \"Student\" of a University!"; Hear Double cote is not allow without using "\".
  2. We can not use "\" single in a string. String s = "I am a \ Student of a University!"; Hear "\" will make an Err.
  3. No method need to split using "\" Simply use "\n" Where you Need.

    Or use another character with it like this

    String s = "Thir is a Tiger.\'I like it very nuch!\'I it a pet!";
    String s2[] = s.split("\'");
    for (int i = 0; i < s2.length; i++) {
        System.out.println(i+" value "+s2[i]);
    }
    

Upvotes: 0

Chit Khine
Chit Khine

Reputation: 850

This problem is solved by using

a.split("\\\\");

Upvotes: 3

Related Questions