Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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();

                  }
                }
                }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
172 views
Welcome To Ask or Share your Answers For Others

1 Answer

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", ""*/"");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...