Removing blank line from String

J

JehanNYNJ

Here is a string with a blank line created when the user hit the enter
key twice..

"Type this first

Hit enter twice and I am here".

How do I compress this String extra blank line so it looks like

"Type this first
Hit enter twice and I am here"

Thanks for any help,
Jehan
 
M

Manish Pandit

You want to remove the 'extra' blank line or any blank line? You can
use StringReader and wrap it within BufferedReader, do a readLine and
if the line being read is empty, do not include it in your output. This
may not be the best solution if the strings are huge though.

-cheers,
Manish
 
T

Thomas Hawtin

Here is a string with a blank line created when the user hit the enter
key twice..

"Type this first

Hit enter twice and I am here".

How do I compress this String extra blank line so it looks like

"Type this first
Hit enter twice and I am here"

I guess something like:

String compressed = str.replaceAll("\n{2,}", "\n");

Tom Hawtin
 
J

JehanNYNJ

I forgot to mention that I am using java 1.1, so the solution would
have to work with this API.

Basically what I have to do is compress all the blank lines of a string
up so that there are no blank lines. So for example if the user
enters..

"This is line one.

I press enter twice now here."

It should be

""This is line one.
I press enter twice now here."

If I can get a code sample, that would be great.

Thanks again,
Jehan
 
M

Manish Pandit

If I can get a code sample, that would be great.
public static String compressNewLines(String string) throws
IOException{
BufferedReader reader = new BufferedReader(new StringReader(string));
StringBuffer out = new StringBuffer();
String subString;
while((subString = reader.readLine())!=null){
if(subString.trim().length()>0) out.append(subString+"\n");
}
return out.toString().trim();
}

-cheers,
Manish
 
J

JehanNYNJ

This works.

Thanks for you help Manish.




Manish said:
public static String compressNewLines(String string) throws
IOException{
BufferedReader reader = new BufferedReader(new StringReader(string));
StringBuffer out = new StringBuffer();
String subString;
while((subString = reader.readLine())!=null){
if(subString.trim().length()>0) out.append(subString+"\n");
}
return out.toString().trim();
}

-cheers,
Manish
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top