str.lastIndexOf(“\”)给出错误
我想从我的字符串中删除最后一次出现的“\”这个特殊字符。 我尝试使用字符串函数
String word = str.substring(str.lastIndexOf("\"));
但每次我收到一个错误,要求提出额外的报价。 与此同时,我发现(“\”“)用来传递”这个特殊的角色。 我该怎么办?
你需要使用
String word = str.substring(str.lastIndexOf("\\"));
字符串中的\
字符是转义特殊字符( ",',\
等等)。所以在它们之前使用\
会使它成为文字 ,这意味着java会将后面的内容视为常规字符。
你可以测试看看是什么
System.out.println("\\");
会打印。 它会打印\
。
所以:
System.out.println("\" "); //would print one like this: " System.out.println("\' "); //would print one like this: '
等等。
\
是一个逃脱角色。 如果你使用"\"
,它就像转义"
字符.Java将其理解为" \" (quote missing)
。因此出现关闭引用的错误。
要解决它,您需要转义\
字符。
String word = str.substring(str.lastIndexOf("\\"));