简体   繁体   English

如何通过\拆分java中的字符串?

[英]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("\\");

这个问题通过使用来解决

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

While you could escape the regular expression to String.split with the somewhat surprising 虽然您可以将正则表达式转义为String.split ,但有点令人惊讶

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 它也可以编译一个PatternPattern.LITERAL然后使用Pattern.split(CharSequence)

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]

Simply use \\n inside the string where need. 只需在需要的字符串内使用\\ n。 No method need to split. 没有方法需要拆分。

  1. "\\" special character in java. “\\”java中的特殊字符。 It is use to skip a character. 它用于跳过一个角色。 Such as String s = "I am a \\"Student\\" of a University!"; 比如String s =“我是一个大学的学生”! Hear Double cote is not allow without using "\\". 如果不使用“\\”,则不允许听到Double cote。
  2. We can not use "\\" single in a string. 我们不能在字符串中使用“\\”单个。 String s = "I am a \\ Student of a University!"; String s =“我是一名大学的学生!”; Hear "\\" will make an Err. 听到“\\”会成为一个错误。
  3. No method need to split using "\\" Simply use "\\n" Where you Need. 没有方法需要使用“\\”拆分只需使用“\\ n”您需要的地方。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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