1+ package  main
2+ 3+ import  "strings" 
4+ import  "fmt" 
5+ 6+ func  removeComments (source  []string ) []string  {
7+  var  code  []string 
8+  wholeLine  :=  strings .Join (source , "\n " ) +  "\n " 
9+  var  tempLine  string 
10+ 11+  for  wholeLine  !=  ""  {
12+  ssIndex  :=  strings .Index (wholeLine , "/*" )
13+  slIndex  :=  strings .Index (wholeLine , "//" )
14+  if  ssIndex  ==  slIndex  {
15+  tempLine  +=  wholeLine 
16+  break 
17+  } else  if  ssIndex  ==  - 1 {
18+  wholeLine  =  curStr (& tempLine , wholeLine , slIndex , "\n " )
19+  } else  if  slIndex  ==  - 1 {
20+  wholeLine  =  curStr (& tempLine , wholeLine , ssIndex , "*/" )
21+  } else  if  ssIndex  >  slIndex  {
22+  wholeLine  =  curStr (& tempLine , wholeLine , slIndex , "\n " )
23+  } else  if  ssIndex  <  slIndex  {
24+  wholeLine  =  curStr (& tempLine , wholeLine , ssIndex , "*/" )
25+  }
26+ 27+  }
28+  for  _ , line  :=  range  strings .Split (tempLine , "\n " ) {
29+  if  line  !=  ""  {
30+  code  =  append (code , line )
31+  }
32+  }
33+  return  code 
34+ }
35+ 36+ func  curStr (tempLine  * string , wholeLine  string , index  int , corres  string ) string {
37+  (* tempLine ) +=  wholeLine [:index ]
38+  wholeLine  =  wholeLine [index  +  2 :]
39+  if  corres  ==  "\n "  {
40+  wholeLine  =  wholeLine [strings .Index (wholeLine , corres ):]
41+  } else 
42+  {
43+  wholeLine  =  wholeLine [strings .Index (wholeLine , corres ) +  len (corres ):]
44+  }
45+  return  wholeLine 
46+ }
47+ 48+ func  main () {
49+  code  :=  []string  {"dsf" , " //sdfsdfa" , " /*fsdfs" , "sdfsdf" , "fsdfsdf" , " sdfasdf */ " , "//sdfsdf" , "%fsdfsdf" , "fefwe" }
50+  //code := []string {"/*Test program */", "int main()", "{ ", " // variable declaration ", "int a, b, c;", "/* This is a test", " multiline ", " comment for ", " testing */", "a = b + c;", "}"} 
51+  // code := []string {"a//*b//*c","blank","d//*e/*/f"} 
52+  //code := []string {"struct Node{", " /*/ declare members;/**/", " int size;", " /**/int val;", "};"} 
53+  result  :=  removeComments (code )
54+  fmt .Println (strings .Join (result , "\n " ))
55+ }
56+ 57+ // a//*b//*c 
58+ // blank 
59+ // d//*e/*/f 
60+ 61+ // ["struct Node{", " /*/ declare members;/**/", " int size;", " /**/int val;", "};" 
62+ // ] 
63+ // struct Node{ 
64+ // /*/ declare members;/**/ 
65+ // int size; 
66+ // /**/int val; 
67+ // }; 
0 commit comments