【问题标题】:Add comment character to lines in a StringBuffer将注释字符添加到 StringBuffer 中的行
【发布时间】:2013-03-13 22:34:45
【问题描述】:

我有一个表示文件的 StringBuffer。
我想在(某些)行的开头添加注释字符。
例如,如果我的内容是这样的:

line  
line  
line  
line-to-comment  
line-to-comment  
line  
line

我想得到以下结果:

line  
line  
line  
#line-to-comment  
#line-to-comment  
line  
line  

顺便说一句,我们的语法不允许多行 cmets(例如 /** ... **/)。
最好的方法是什么?
谢谢

【问题讨论】:

    标签: java parsing stringbuffer


    【解决方案1】:

    我最终做了什么:

    String uncommentedLines = myFile.substring(startIndex, endIndex);  
    String commentedBlock = "#" + uncommentedLines.replaceAll(System.lineSeparator(), System.lineSeparator()+"#");  
    myFile.replace(startIndex, endIndex, commentedBlock);
    

    【讨论】:

      【解决方案2】:

      最简单的解决方案可能是直接的字符串操作。

      StringBuffer sb = ....:
      int pos = sb.indexOf("line-to-comment");
      sb.insert(pos, "#");
      

      如果您重复执行此操作,您需要检查 pos-1 处的字符是否与“#”不同。

      至少这是我应该做的……

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-02-08
        • 1970-01-01
        • 2012-02-05
        • 2017-04-28
        • 1970-01-01
        • 2012-08-24
        • 2010-10-02
        相关资源
        最近更新 更多