Reputation: 143
I write a bracket checker in Java and have problems searching for single quotes in the text. if I have a String like e.g. the following (!in this case it's the text I'm interested not the code):
else if (line.charAt(i)=='\''||line.charAt(i)=='\"'){
in the debugger I see that after the first equals sign I get the following characters in my String:
0 = '
1 = \\\
2 = '
3 = '
How can I combine 1 and 2 - so that he doesn't read the second ' as ' anymore? I thought it is done with backslash - but obviously I'm doing something wrong.
If the code is of any help: This is how I treat single and double quotes:
Stack <Character> theStack = new Stack<Character>();
// loop through file line per line
String line;
else if (line.charAt(i)=='\'' ||line.charAt(i)=='\"'){
// check whether there is already one of them on top
if (line.charAt(i)== '\'' && theStack.peek()=='\''){
theStack.pop();
}
else if (line.charAt(i)== '\"' && theStack.peek()=='\"'){
theStack.pop();
}
// else push new one on top
else {
theStack.push(line.charAt(i));
}
}
It fails because in the line shown above it reads three single/double quotes. It should read only two of them. I do not understand how I can avoid the Scanner to read the second single/double quote in the statement shown above as a single quote. I thought it is done with backslash.
Upvotes: 0
Views: 983
Reputation: 51711
Just modify your if
condition as follows
else if ((line.charAt(i) == '\'' || line.charAt(i) == '\"')
&& line.charAt(i-1) != '\\') {
This would ignore all quotes that have been escaped with a backslash i.e. should not be treated as a closing quote and pop your character stack. You can further simplify your if-else
blocks as
// check whether there is already one of them on top
if (line.charAt(i) == theStack.peek()) { // un-boxing to char
theStack.pop();
}
// else push new one on top
else {
theStack.push(line.charAt(i));
}
This works because the parent else-if
block has already made sure that the line character is either '
or "
and so we can go ahead and directly compare it with the head of your character stack.
Upvotes: 1