Remove/collapse multiple newline characters in Java
Description
The following code shows how to remove/collapse multiple newline characters.
Example
// w w w . j av a2s .c om
public class Main {
public static void main(String[] argv){
String lines = "java2s.com\n\n\n\n\na\n\n\nb\n\nc";
System.out.println(lines);
lines = collapseNewlines(lines);
System.out.println(lines);
}
/**
* Remove/collapse multiple newline characters.
*
* @param argStr string to collapse newlines in.
* @return String
*/
public static String collapseNewlines(String argStr)
{
char last = argStr.charAt(0);
StringBuffer argBuf = new StringBuffer();
for (int cIdx = 0 ; cIdx < argStr.length(); cIdx++)
{
char ch = argStr.charAt(cIdx);
if (ch != '\n' || last != '\n')
{
argBuf.append(ch);
last = ch;
}
}
return argBuf.toString();
}
}
The code above generates the following result.
Home »
Java Tutorial »
Java Data Type »
Java Tutorial »
Java Data Type »