How can I ignore comments statements /*…*/ when i

2019-09-20 06:05发布

问题:

How can i ignore the comment statements that begin with "/*" and ends with "*/" for example: /*the problem is..*/ or /* problem is very difficult */ ,,i want to remove these statement when i reading java file line by line

public class filename1 {

      public static void main (String args[])

        {

    try {

      fileName = "C:\\NetBeansProjects\\filename\\src\\filename\\filename.java";

      FileReader fr = new FileReader(fileName);

     BufferedReader br = new BufferedReader(fr);

        line = br.readLine();

        while (line !=null) {


       for( int i=0;i<line.length();i++)

         {            
           b=line.indexOf("/",i);         

           ee=line.indexOf("*",i);         
           if(b!=-1 && ee!=-1)

           v=line.indexOf("*/",i);
             if (v==-1)
              line=" ";
                  }


                System.out.println(line);


                 line = br.readLine(); 
                          }}

                  catch (IOException e)
               {   
                e.printStackTrace();

                  }
                }
                }

回答1:

Simply include:

int index =  str.indexOf("/*");

while(index != -1) {
    str = str.substring(0, index) + str.substring(str.indexOf("*/")+2);
    index =  str.indexOf("/*");
}

Edit: Assuming that you have to account for fragments where you have a comment interrupted by the start or end of the string:
Edit2: Now.. Also assuming that you have to take into account for literal string "/*" or "*/"

str = str.replace("\"/*\"", "literal_string_open_comment");
str = str.replace("\"*/\"", "literal_string_close_comment");

int start =  str.indexOf("/*"), end = str.indexOf("*/");

while(start > -1 || end > -1) {
    if(start != -1) {
        if(end != -1) {
            if(end < start) {
                str = str.substring(end+2);
            } else {
                str = str.substring(0, start) + str.substring(end+2);
            }
        } else {
            str = str.substring(0, start);
        }
    } else {
        str = str.substring(end+2);
    }

    start =  str.indexOf("/*"); 
    end = str.indexOf("*/");
}

str = str.replace("literal_string_open_comment", "\"/*\"");
str = str.replace("literal_string_close_comment", "\"*/\"");