我写了一个方法来从 C++ 源文件中删除单行注释:
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
}
}<p></p>
<pre><code>if(!process)
{
def line = it.substring(0,singleCommentPos)
builder << line << "\n"
}
else
{
builder << it << "\n"
}
</code></pre>
<p>}
else
{
builder << it << "\n"
}
}
return builder.toString()
}
</p>
我测试了它:
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
""")
它产生这个输出:
this is a test inside double quotes "//inside double quotes" this is a test inside single quotes '//inside single quotes' two single
我是否遗漏了一些案例?
最佳答案
有趣的是由trigraphs组成的和续行。我个人最喜欢的是:
/??/
* this is a comment *??/
/
关于c++ - 你能给我一些 C++ 中奇怪的单行注释的例子吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1618419/