[英]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. 尝试删除由StringBuilder制作的文件中2个空行以外的所有多余空行。 The code is in groovy so I seem to not understand why simple java procedure don't seem to work.
该代码是普通的,所以我似乎不明白为什么简单的Java过程似乎不起作用。 Tried 3 things... Any suggestions?
尝试了3件事...有什么建议吗? 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
. replaceAll()
不会修改StringBuilder
。 Instead, it returns a new String
. 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
: 最简单的方法是使用带有适当正则表达式的
replaceAll()
,然后使用replace()
获取replaceAll()
的输出,并使其成为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) 您需要使用++ i(预增量)而不是i ++(后增量)
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# 在C,C ++,Java和C#中检出前后递增运算符的行为
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.