开发者

How to check for back slash in input?

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.

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.


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:

  • JLS 3.10.4 - Character Literals
  • JLS 3.10.6 - Escape Sequences


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.

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("\\"));
            }
        }
    }

}


A backslash character can be represented in Java source code as '\\'.

final char[] chars = strLine.toCharArray();
for (int i = 0; i < chars.length; i++) {
    if (chars[i] == '\\') {
        // is a backslash
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜