2013-03-24 35 views
-4

我有一个表示文件的StringBuffer。
我想在(某些)行的开头添加注释字符。
例如,如果这是我的内容看起来像:将评论字符添加到StringBuffer中的行

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

我希望得到如下结果:

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

顺便说一句,我们的语法不允许多线评价(如作为/ ** ... ** /)。
什么是最好的方法?
谢谢

+3

那你试试? – 2013-03-24 11:41:25

回答

0

我最终什么事做:

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

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

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

如果你反复这样做,你需要在POS-1,检查字符是从“#”不同。

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