[英]How do I find a character followed by a character in a char array Java?
[英]Java: read an escape character as '\' followed by a char?
我正在编写编译器的扫描器,并且在输入“ {\\ 0}”时遇到麻烦。 我的扫描仪应该做的是:跳过空白,识别'{',识别无效的字符,识别'}',跳过空白,检测eof。 相反,它只会跳过\\ 0。
我的扫描仪是以这种方式完成的,它将跳过任何“无用的”字符(值小于或等于'')。 因此,将跳过\\ 0字符,而不是将其作为无效的字符常量进行处理(我尚未实现此错误情况,但是无论如何我的代码都没有进入thi的readCharConst(Token t)
函数中案件...)。 我想知道的是我应该怎么做才能使其将“ \\ 0”处理为“ \\”,后跟“ 0”而不是单个字符。
这是我的一些功能:
public Token next() {
while (ch <= ' ') {
nextCh(); // skip blanks, tabs, eols
}
Token t = new Token(Kind.none, line, col);
switch (ch) {
// cases for identifiers, numbers, meta-chars, ...
case '\'':
readCharConst(t);
break;
default:
error(t, Message.INVALID_CHAR, ch);
nextCh();
t.kind = Kind.none;
}
return t;
}
与:
public void nextCh() {
try {
ch = (char) in.read();
if (ch == LF) { // detects new_line
col = 0;
line++;
} else if (ch != EOF) { // do not increment col for EOF
col++;
}
} catch (IOException e) {
ch = EOF;
e.printStackTrace();
}
}
和:
private void readCharConst(Token t) {
nextCh();
if (ch == '\'') {
error(t, Message.EMPTY_CHARCONST);
} else {
t.val = (int) ch;
t.kind = Kind.charConst;
nextCh();
if (ch != '\'') {
error(t, Message.MISSING_QUOTE);
}
nextCh();
}
}
注意:通过用while(ch == ' ' || ch == '\\t' || ch == '\\n' || ch == '\\r'|| ch == '\\b' || ch == '\\f' || ch == '\\"' || ch == '\\'' || ch == '\\\\')
代替while (ch <= ' ')
解决我的问题while(ch == ' ' || ch == '\\t' || ch == '\\n' || ch == '\\r'|| ch == '\\b' || ch == '\\f' || ch == '\\"' || ch == '\\'' || ch == '\\\\')
,以便检测所有转义序列并使用默认条件处理其余部分。尽管如此,我的课程幻灯片仍将\\ r,\\ n,\\ t视为char常量(在我看来,这使我进入了停顿,除非我能找到一种将序列后跟'\\'后跟一个字符的方式)。
其实我想我明白了。 这与读取'\\'无关,而只是跳过正确的字符。 这些字符是转义序列,其值小于''(十进制的ASCII值:32)。 因此,要跳过的字符是'\\b'
(val:8), '\\t'
(val:9), '\\n'
(val:10), '\\f'
(val:12), '\\r'
(val:13),而其他所有设置将由我的交换机的默认情况处理。 因此,我将时间改为:
while (ch == ' ' || ch == '\b' || ch == '\t' || ch == '\n' || ch == '\f' || ch == '\r')
// skip blanks and all esc. seq. with value < ' ' (others, like '\'' might need to be treated)
nextCh();
实际上,这里的情况'\\'与此处无关(与我提供的输入不匹配),因此这可能就是我不赞成投票的原因。 这种情况只有在我试图识别上述转义序列时才起作用,如果它们明确地出现在输入中(例如,输入" '\\\\n' "
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.