Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

238
Vistas
Java String split returns length 0
public int lengthOfLastWord(String s) {
        s.replaceAll("\\s", "");
        String[] splittedS = s.split("\\s+");
        if(splittedS.length == 1 && splittedS[0].equals("")) return 0;
        return splittedS[splittedS.length - 1].length();
    }

I tested it out with the string " ", and it returns that the length of splittedS is 0.

When I trimmed the String did I get " " -> "", so when I split this, I should have an array of length with with the first element being ""?

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

Java Strings are immutable so you have to store the reference to the returned String after replacement because a new String has been returned. You have written,

s.replaceAll("\\s", "");

But write, s = s.replaceAll("\\s", ""); instead of above.

Wherever you perform operations on String, keep the new reference moving further.

over 4 years ago · Santiago Trujillo Denunciar

0

The call to replaceAll has no effect, but since you split on \\s+, split method works exactly the same: you end up with an empty array.

Recall that one-argument split is the same as two-argument split with zero passed for the second parameter:

String[] splittedS = s.split("\\s+", 0);
//                                  ^^^

This means that regex pattern is applied until there's no more changes, and then trailing empty strings are removed from the array.

This last point is what makes your array empty: the application of \\s+ pattern produces an array [ "" ], with a single empty string. This string is considered trailing by split, so it is removed from the result.

This result is not going to change even if you fix the call to replaceAll the way that other answers suggest.

over 4 years ago · Santiago Trujillo Denunciar

0

You need to re assign the variable

s=s.replaceAll(...)
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda