Trying to remove any extra empty lines beyond 2 empty lines in a file made from a StringBuilder. The code is in groovy so I seem to not understand why simple java procedure don't seem to work. Tried 3 things... Any suggestions? See code snippets below
private static final removeExtraLines1(StringBuilder text)
{
String twoLines = "MIAW";
Pattern extraLines = Pattern.compile("\n")
text.replaceAll(extraLines, twoLines);
}
private void removeExtraLines(StringBuilder text)
{
int i = 0;
while(i < text.length()-1)
{
if(text.charAt(i) == System.lineSeparator() && text.charAt(i++) == System.lineSeparator())
{
text.deleteCharAt(i++);
System.out.println("REPLACED AN EMPTY LINE");
}
}
}
@Override
String toString()
{
def padding = " " * (4 * (level - 1) )
padding + "cat level $level [$title]: " +
contained.collect {
it.toPaddedString(padding) }
////My Code
String twoLines = System.lineSeparator()+System.lineSeparator();
Pattern extraLines = Pattern.compile(System.lineSeparator()+ System.lineSeparator()+ System.lineSeparator()+System.lineSeparator())
_toString().replaceAll(extraLines, twoLines)
}
The issue here is that each approach has a mistake:
replaceAll()
does not modify the StringBuilder
. Instead, it returns a new String
. Also, the regular expression is incorrect. The easiest method is to use replaceAll()
with a proper regular expression, and then use replace()
to take the output of replaceAll()
and make it the entire content of the StringBuilder
:
private static final removeExtraLines1(StringBuilder text) {
text.replace(0, text.size(), builder.replaceAll('\n\n', '\n'))
}
you need to use ++i (pre increment) instead of i++ (post increment)
if(text.charAt(i) == System.lineSeparator() && text.charAt(++i) == System.lineSeparator())
{
text.deleteCharAt(++i);
System.out.println("REPLACED AN EMPTY LINE");
}
checkout Pre & post increment operator behavior in C, C++, Java, & C#
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.