Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

80
Vistas
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!
9 months ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

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!
9 months ago · Santiago Trujillo Denunciar

0

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

String removedEmptyLines = text.replaceAll("(?m)^[ \t]*\r?\n", "");
9 months ago · Santiago Trujillo Denunciar

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 .

9 months ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos