Search code examples
javaparsingstringbuffer

Add comment character to lines in a StringBuffer


I have a StringBuffer representing a file.
I would like to add comment characters at the beginning of (some of the) lines.
For example, if this is how my content looks like:

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

I would like to get the following results:

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

BTW, Our syntax doesn't allow multi lines comments (such as /** ... **/).
What would be the best approach?
Thanks


Solution

  • What I ended up doing:

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