Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

212
Views
Replace multiple line spacings with one line spacing?

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!
over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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!
over 4 years ago · Santiago Trujillo Report

0

Try Bart Kiers's answer to remove empty lines within a string.

String removedEmptyLines = text.replaceAll("(?m)^[ \t]*\r?\n", "");
over 4 years ago · Santiago Trujillo Report

0

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 .

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!