Java 如何检查输入中的反斜杠?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3173773/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check for back slash in input?
提问by Primal Pappachan
I have to check for character sequences like \chapter{Introduction} from the strings read from a file. To do this I have to first check for the occurence of backslash.
我必须从文件中读取的字符串中检查字符序列,如 \chapter{Introduction}。为此,我必须首先检查是否出现反斜杠。
This is what I did
这就是我所做的
final char[] chars = strLine.toCharArray();
char c;
for(int i = 0; i<chars.length; i++ ){
c = chars[i];
if(c == '\' ) {
}
}
But the backslash is treated as an escape sequence rather than a character.
但是反斜杠被视为转义序列而不是字符。
Any help on how to this would be much appreciated.
任何有关如何做到这一点的帮助将不胜感激。
采纳答案by BalusC
The backward slash is an escape character. If you want to represent a real backslach, you have to use two backslashes (it's then escaping itself). Further, you also need to denote characters by singlequotes, not by doublequotes. So, this should work:
反斜杠是转义字符。如果你想代表一个真正的反斜杠,你必须使用两个反斜杠(然后它自己转义)。此外,您还需要用单引号而不是双引号来表示字符。所以,这应该有效:
if (c == '\')
See also:
也可以看看:
回答by David Z
A backslash character can be represented in Java source code as '\\'
.
反斜杠字符可以在 Java 源代码中表示为'\\'
.
final char[] chars = strLine.toCharArray();
for (int i = 0; i < chars.length; i++) {
if (chars[i] == '\') {
// is a backslash
}
}
回答by bedwyr
You might also consider using the contains()
and/or indexOf()
methods for String
. They will save you the trouble of iterating over each character in any given line.
您也可以考虑使用contains()
和/或indexOf()
方法String
。它们将为您省去在任何给定行中迭代每个字符的麻烦。
Here's an example:
下面是一个例子:
public class Test {
public static void main(String[] args) {
if(args.length < 1) {
System.out.println("java Test string1 string2 ...");
System.exit(1);
}
for (String inputStr : args) {
if(inputStr.contains("\")) {
System.out.println("Found at: " + inputStr.indexOf("\"));
}
}
}
}