Count characters without empty spaces

Asked

Viewed 4,604 times

2

I have to count the number of characters in a string, but when there is empty space it is counted as a character. How do I remove these empty spaces? Any tips?

  • 2

    Hello Felipe. Post for us what you already have ready, it is easier to adapt your example than from scratch.

  • Tip, search Google. Where’s your code so we can see your error? It’s important to post code for it to be analyzed. Now if you don’t have code Search in Google.

3 answers

2

Alternatively, you could use a function where the entire string was traversed and the isspace was used to restrict counting of blank characters:

#include <ctype.h>

using namespace std;

int contarCaracteres(const string& str)
{
    int contador = 0;
    for(int i = 0; i < str.size(); ++i) 
    {
        if (!isspace(str[i]))
            ++contador;
    }

    return contador;
}

Obs: the isspace considers that a character is blank in the following cases:

  • ' '
  • '\t'
  • '\n'
  • '\v'
  • '\f'
  • '\r'
  • 2

    Could be const std::string& str in the function parameter to avoid a copy.

  • Oh it’s true, as this application is limited to just doing this count, it’s interesting to keep up the good practice of passing class arguments using references and not directly by value. Thanks for the @Lucasnunes reminder (:

1

If your goal is just to count the different elements of white space, you should take a look at the function std::count_if of the standard algorithm library ( <algorithm> ).

With this function it is possible to count how many elements of an interval obey a predicate. Therefore, just use as a predicate for std::count_if a function that returns true when the character is not a blank space and false when it is. For this purpose we can use the negation of the function std::isspace.

int main() {
    auto s = std::string{ "25 caracteres sem os espacos." };
    auto n = std::count_if( std::begin( s ), std::end( s ),
                            [](char c){ return !std::isspace( c ); } );

    std::cout << "String: \"" << s << "\"\n";
    std::cout << "Quantidade de caracteres: " << s.size( ) << "\n";
    std::cout << "Quantidade de caracteres nao brancos: " << n << std::endl;
    return 0;
}

Follow an example running from the proposed solution: http://ideone.com/Wwpl5I

1

To do this you can use the function std::erase.

#include <iostream>
#include <algorithm>

using namespace std;

int main()
{
    string str = "Stack Overflow em Portugues";
    str.erase(remove(str.begin(),str.end(),' '),str.end());
    cout << str << endl;
    cout << "Lenght  " << str.length() << endl;
    return 0;
}

The result will be:

inserir a descrição da imagem aqui

Browser other questions tagged

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