How to check backslash in input?

I need to check a sequence of characters, such as \ chapter {Introduction}, from lines read from a file. To do this, I must first check for a 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, not a character.

Any help on how that would be greatly appreciated.

+4
source share
3 answers

The inverse is an escape character. If you want to imagine a real backward bounce, you should use two backslashes (then they escape themselves). In addition, you also need to mark characters with single quotes, not double quotes. So this should work:

 if (c == '\\') 

See also:

+8
source

You can also use the contains() and / or indexOf() methods for String . They save you from having to iterate each character on any line.

Here is 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("\\")); } } } } 
+4
source

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

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

Source: https://habr.com/ru/post/1314653/


All Articles