Search code examples
c++visual-studiostdstringtolowerisalpha

Using tolower() and isalpha() to on a given string and set their output into another string


I want to pass a string to the compiler for example "Mr. Adam, I am Eve" . I want to lower the case of that phrase and remove all the punctuation marks and spaces by using (isalpha), i.e.- afterwards the string should be: mradamiameve which will be stored in another string called result for example. I need help with this. Any suggestions?

This is what I have done so far, which does not work:

#include <iostream>
#include <string>

using namespace std;

int main(int argc, char* argv[]) 
{
    string str = "Mr. Adam, I am Eve";
    string result;
    for (size_t i = 0; i < str.length(); ++i)
    {
        if (isalpha(str[i]))
        {       
            result[i] = str[i];
        }
    }

    // here str should be = "mradamiameve" YET it is still "Mr. Adam, I am Eve" 
    cout << "after using to tolower() and isalpha() str is:" << str << endl; 
    return 0;
}

Solution

  • If you are on c++11 you could use range based loop:

    #include <iostream>
    #include <cctype>
    #include <string>
    
    int main()
    { 
        std::string result, str = "Mr. Adam, I am Eve";
    
        for (unsigned char c : str)
            if (std::isalpha(c))
                result += std::tolower(c);
    
        std::cout << result << std::endl;
    }