问题描述
|
我必须删除文件中的所有注释。引号中的注释定界符应视为文本,并且必须打印到屏幕上。注释内的引号被视为其他注释,必须将其删除。
当涉及单引号时,以下switch语句存在问题,这给了我一个错误。
我知道错误是什么,但我不知道如何解决。
import java.io.*;
public class Q3{
public static final int STATE_norMAL = 0;
public static final int STATE_QUOTE_SINGLE = 1; // this:\'\'
public static final int STATE_QUOTE_DOUBLE = 5; // this: \"\"
public static final int STATE_SLASH = 2; // this: /
public static final int STATE_SLASH_STAR = 3; // this: /* *
public static final int STATE_COMMENT = 4; // this: /* */ || /* only
public static void main(String[] argv) throws IOException{
final int EOF = -1;
InputStreamReader in = new InputStreamReader(system.in);
int c;
char[] buffer = new char[2];
int currState = Q3.STATE_norMAL;
char outChar;
while((c = in.read()) != EOF){
outChar = (char) c;
switch (outChar){
case \'/\' :
/* if(currState == Q3.STATE_QUOTES)
currState ==Q3.STATE_QUOTES; */
if(currState == Q3.STATE_norMAL)
currState = Q3.STATE_SLASH;
else if(currState == Q3.STATE_COMMENT)
currState = Q3.STATE_norMAL;
break;
case \'*\':
if(currState == Q3.STATE_SLASH)
currState = Q3.STATE_COMMENT;
break;
case \'\"\':
if(currState == Q3.STATE_norMAL)
currState = Q3.STATE_QUOTE_DOUBLE;
if(currState == Q3.STATE_QUOTE_DOUBLE)
currState = Q3.STATE_norMAL;
break;
*case \'\'\':
if(currState == Q3.STATE_norMAL)
currState = Q3.STATE_QUOTE_SINGLE;
if(currState == Q3.STATE_QUOTE_SINGLE)
currState = Q3.STATE_norMAL;
break;*
}
if(currState != Q3.STATE_COMMENT)
System.out.print(outChar);
}
}
}
解决方法
您将不得不转义单引号。
用这个
case \'\\\'\'
, 请尝试以下操作:
str = str.replaceAll(\“ /.+/ \”,\“ \”);我不确定上下文,但是想法是使用正则表达式而不是像您正在尝试的那样简化代码。