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:20

You don't seem to handle escaped quotes, like:

"Comment\"//also inside string"

versus

"Comment"//not inside string"
查看更多
够拽才男人
3楼-- · 2019-09-15 10:28

I think you can't handle

  puts("Test \
    // not a comment");

and this is also likely to make problems:

  puts("'"); // this is a comment
查看更多
虎瘦雄心在
4楼-- · 2019-09-15 10:29

The fun ones are formed by trigraphs and line continuations. My personal favorite is:

/??/
* this is a comment *??/
/
查看更多
兄弟一词,经得起流年.
5楼-- · 2019-09-15 10:30

The handling of \ character at the end of the line is performed at the earlier translation phase (phase 2) than replacement of comments (phase 3). For this reason, a // comment can actually occupy more than one line in the original source file

// This \
whole thing \
is actually \
a single comment

P.S. Oh... I see this is already posted. OK, I'll keep it alive just for mentioning phases of translation :)

查看更多
贼婆χ
6楼-- · 2019-09-15 10:33
// Single line comments can\
actually be multi line.
查看更多
Emotional °昔
7楼-- · 2019-09-15 10:37

This is always a favourite:

// Why doesn't this run?????????????????????/
foo(bar);
查看更多
登录 后发表回答