How do I replace multiple line spacings with one line spacing in a string?
I want this:
Hello!
Hello again!
to be converted to this:
Hello!
Hello again!
or this:
Hello!
Hello again!
You can use :
str.replaceAll("\n+", "\n");
Here is an example :
String str = "Hello!\n"
+ "\n"
+ "\n"
+ "\n"
+ "\n"
+ "\n"
+ "\n"
+ "\n"
+ "Hello again!";
str = str.replaceAll("\n+", "\n");
System.out.println(str);
Output
Hello!
Hello again!
Try Bart Kiers's answer to remove empty lines within a string.
String removedEmptyLines = text.replaceAll("(?m)^[ \t]*\r?\n", "");
You can make a Queue . Read line by line If first character of line is not a new line character , include it in the queue. Otherwise if its a space just peek last element is queue, dont add it if the queue last element was also new line .
So when you print also , you have the liberty you want to print new line character or not .