//类似于有限状态机
import java.io.FileReader;
import java.io.IOException;
public class RemoveComment {
//遍历字符串,记录闭合状态
public static String removeComment(String src){
StringBuffer sb = new StringBuffer();
int currentState=-1; //0=",1=//,2=/*
for(int i=0;i<src.length();i++){
char c = src.charAt(i);
if(c == '\"'){
if(currentState==-1){
currentState = 0;
sb.append(c);
}else if(currentState==0){
currentState = -1;
sb.append(c);
}
}else if(c=='/'){
i++;
if(i==src.length()){
if(currentState!=1&¤tState!=2){
sb.append("/");
}
break;
}
char next = src.charAt(i);
if(next=='/'){
if(currentState ==-1){
currentState = 1;
}else if(currentState == 0){
sb.append("//");
}
}else if(next=='*'){
if(currentState ==-1){
currentState = 2;
}else if(currentState == 0){
sb.append("/*");
}
}else if(next=='\\'){
if(currentState!=1&¤tState!=2){
sb.append("/");
}
i--;
}else if(next=='\\'){
if(currentState!=1&¤tState!=2){
sb.append("/");
}
i--;
}
else{
if(currentState!=1&¤tState!=2){
sb.append("/").append(next);
}
}
}else if(c=='*'){
i++;
if(i==src.length()){
if(currentState!=1&¤tState!=2){
sb.append("*");
}
break;
}
char next = src.charAt(i);
if(next=='/'){
if(currentState == 2){
currentState = -1;
}else if(currentState!=1){
sb.append("*/");
}
}else if(next=='\\'){
if(currentState!=1&¤tState!=2){
sb.append("*");
}
i--;
}else{
if(currentState!=1&¤tState!=2){
sb.append("*").append(next);
}
}
}else if(c=='\n'){
if(currentState == 1){
currentState = -1;
}
sb.append("\n");
}else if(c=='\\'){
i++;
if(i==src.length()){
if(currentState!=1&¤tState!=2){
sb.append("\\");
}
}
char next = src.charAt(i);
if(currentState!=1&¤tState!=2){
sb.append("\\").append(next);
}else{
i--;
}
}else{
if(currentState!=1&¤tState!=2){
sb.append(c);
}
}
}
return sb.toString();
}
public static void main(String[] args) throws IOException {
FileReader fr = new FileReader("D:\\workspace\\MyTest\\src\\test.txt");
char[] cbuf = new char[4000];
int length = fr.read(cbuf);
String src = new String(cbuf,0,length);
src = removeComment(src);
System.out.println(src);
}
}