去掉comments

三种comments:

 1 /* Test program */ 
 2 
 3    int main()  
 4 
 5    {           
 6 
 7       // variable declaration 
 8 
 9       int a, b, c;    
10 
11       /* This is a test  
12 
13           multiline     
14 
15           comment for   
16 
17           testing */      
18 
19       a = b + c;       
20 
21    } 

 

 1 import java.util.*;
 2 public class removeComments{
 3     public static void main(String [] args){
 4         String file = "   /* Test program */ \n" + 
 5                   "   int main()  \n" +
 6                   "   {           \n" +
 7                   "      // variable declaration \n" +
 8                   "      int a, b, c;    \n" +
 9                   "      /* This is a test  \n" +
10                   "          multiline     \n" +
11                   "          comment for   \n" +
12                   "          testing */      \n" +
13                   "      a = b + c;       \n" +
14                   "   }           \n";
15         System.out.println(file);
16         System.out.println(removeComments(file));
17     }
18 
19     private static String removeComments(String s){
20         if(s == null || s.length() == 0){
21             return s;
22         }
23         StringBuilder res = new StringBuilder();
24         boolean sCom = false;
25         boolean mCom = false;
26 
27         for(int i = 0; i<s.length(); i++){
28             // System.out.println("i is " + i + "sCom, mCom  = " + sCom + mCom);
29             if(sCom && (s.charAt(i) == '\n')){
30                 System.out.println("i is " + i);
31                 sCom = false;
32             }else if(mCom && s.charAt(i) == '*' && i+1<s.length() && s.charAt(i+1) == '/'){
33                 mCom = false;
34                 i++;
35             }else if(sCom || mCom){
36                 continue;
37             }else if(s.charAt(i) == '/' && i+1 < s.length() && s.charAt(i+1) == '/'){
38                 sCom = true;
39                 i++;
40             }else if(s.charAt(i) == '/' && i+1 <s.length() && s.charAt(i+1) == '*'){
41                 mCom = true;
42                 i++;
43             }else{
44                 res.append(s.charAt(i));
45             }
46         }
47         return res.toString();
48     }
49 
50 
51 }

 

posted @ 2016-03-09 09:47  Dylan_Java_NYC  阅读(206)  评论(0编辑  收藏  举报