开发者

How to find String.indexOf("\")?

I need to get the substring that appears before a bunch of \r\n\开发者_StackOverflowr\n junk. So I want to geto the first /that appears. indexOf("\") is not accepted. String.indexOf("\") does not match the first . ????? Thanks


If you're looking for the first occurrence of \n in a string then searching for \\ won't help. You need to look for \n.

String.indexOf("\n")

Note that \n is one character, not two. It's an escape sequence that evaluates to the character with ASCII value 10.


String s1 = "LINE1\r\n\r\nLINE2";
Matcher matcher = Pattern.compile(".+").matcher(s1);
if (matcher.find()) {
    System.out.println(matcher.group());
} else {
    System.out.println("String contains no character other than \\n and \\r");
}

or a bit more perverted:

String s1 = "LINE1\r\n\r\nLINE2";
BufferedReader br = new BufferedReader(new StringReader(s1));
try {
    System.out.println(br.readLine());
} finally {
    br.close();
}

Output in both cases: LINE1


indexOf("/") 

should work fine. Why do you say it is not?


Works fine for me:

System.out.println( "abc//def//".indexOf("/") );

Post your SSCCE demonstrating the problem.


Why does indexOf('/') not work? Does it return the wrong index? Forward slashes should be fine -- backward slashes (\) are escape characters.


if '\' is what you are trying to find, use .indexOf("\");

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜