How to count characters from a String ignoring whitespace?

Asked

Viewed 2,337 times

0

I’m trying to make a return in the variable to count how many letters there are in the typed word and ignore the typed spaces, but I don’t know how to join the length with the trim, says the following message:

Cannot invoke Trim() on the Primitive type int.

    public Integer contaCarateresSemEspaços(String texto) {
    return texto.length().trim();
}

3 answers

5


length is a class method String, this method returns an integer.

trim is also a class method String, but you are invoking trim on the return of length, which is an integer. Integers do not have the method trim, therefore the mistake.

If on the other hand you were invoking the methods in the following order:

texto.trim().length()

First trim would be executed, returning a String, and then length would run on that String returned, which is a valid code.

However trim will only remove the spaces at the beginning and end of your String, if you want to remove all blanks, you will have to replace them with the method replaceAll:

texto.replaceAll("\\s","").length()
  • 1

    Just remembering that \s will also remove other characters, such as TAB and line breaks (depending on the string and what you need, it may make a difference or not). If you want to remove only the spaces, use replaceAll(" ", "")

3

Good evening, if you want to count only the characters the function Trim() is not indicated, it removes only the spaces of the beginning and end of the string. Instead we use the function Replace().

Example:

        string var = "meu valor estatico";
        Console.WriteLine(var.Replace(" ", "").Length);
  • Perfect, I forgot to say that I also need to remove the spaces from the beginning and end of the string, how to do ?

  • If you want to remove only the start and end use the Trim() function, rimed kkkk.

2

If you change the return order of your method, the error will no longer happen, however it will not do what you want.

The sensible thing would be for you to return the value length after removing all blanks:

return texto.replace(" ", "").length();

This way you will return the number of characters without the blanks.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.