Can you give me examples of odd single line commen

2019-09-15 09:44发布

I wrote a method to remove single line comments from a C++ source file:


def stripRegularComments(text) {
  def builder = new StringBuilder()
  text.eachLine {
   def singleCommentPos = it.indexOf("//")
   def process = true
   if(singleCommentPos > -1)
   {
    def counter = 0
    it.eachWithIndex 
    { obj,i ->
     if((obj == '\'') || (obj == '"'))
      counter++
     if(i == singleCommentPos)
     {
      process = ((counter % 2) == 1)
      if(!process)
       return
     } 
    }

if(!process)
{
 def line = it.substring(0,singleCommentPos)
 builder << line << "\n"
}
else
{
 builder << it << "\n" 
}

} else { builder << it << "\n" } } return builder.toString() }

And I tested it with:

println a.stripRegularComments("""
this is a test inside double quotes "//inside double quotes"
this is a test inside single quotes '//inside single quotes'
two// a comment?//other
single //comment
""")

It produces this output:

this is a test inside double quotes "//inside double quotes"
this is a test inside single quotes '//inside single quotes'
two
single

Are there some cases I'm missing?

7条回答
成全新的幸福
2楼-- · 2019-09-15 10:39

I think you are missing the /* comment */ case.

查看更多
登录 后发表回答