Count characters without empty spaces

2

I have to count the number of characters in a string, but when empty, it counts as a character. How do I remove these gaps? Any tips?

    
asked by anonymous 28.03.2014 / 17:20

3 answers

2

Alternatively you could use a function where the entire string was run and isspace was used to restrict the count of characters that were blank:

#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;
}

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

  • ''
  • '\ t'
  • '\ n'
  • '\ v'
  • '\ f'
  • '\ r'
28.03.2014 / 17:43
1

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

#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:

    
28.03.2014 / 17:36
1

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

With this function you can count how many elements of a range obey a predicate. So, just use a predicate to 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 denial 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;
}

Here is an example of running the proposed solution: link

    
31.03.2014 / 15:56