简体   繁体   中英

Groovy removing extra empty lines in StringBuilder Object

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

Regex doesn't do anything.

private static final removeExtraLines1(StringBuilder text)
{
    String twoLines = "MIAW";
    Pattern extraLines = Pattern.compile("\n")
    text.replaceAll(extraLines, twoLines);
}

My own method that deleteCharAt doesn't work too?

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");
        }
    }
}

Modifying the toString() method says regex method replaceAll is deprecated.

@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:

  1. replaceAll() does not modify the StringBuilder . Instead, it returns a new String . Also, the regular expression is incorrect.
  2. Improper use of the post/pre-increment, as stated by Vijay.
  3. OK, I have no idea. I gave up trying to understand the third approach.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM