Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

239
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

0

You need to re assign the variable

s=s.replaceAll(...)
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda