将注释字符添加到StringBuffer中的行

时间:2013-03-24 11:40:09

标签: java parsing stringbuffer

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

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

我想得到以下结果:

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

BTW,我们的语法不允许多行注释(例如/ ** ... ** /) 什么是最好的方法?
感谢

2 个答案:

答案 0 :(得分:0)

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

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

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

至少那是我应该做的......

答案 1 :(得分:0)

我最终做了什么:

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