Search code examples
c++algorithmstdstringalphabet

How to identify string is containing only number?


How to print only text in a string? I want to print only abc from.

string numtext = "abc123";

Here is the full code:

#include <stdio.h>

int main()
{
    string text = "abc123";

    if (text.matches("[a-zA-Z]") //get an error initialization makes integer from pointer without a cast
    {
        printf("%s", text);
    }
    getch();
}

My string contains both numbers and letters and I want to print letters only. But I get an error. What am I doing wrong?


Solution

  • First of all, there is no member function called std::string::matches available in the standard string library for this case.

    Secondly, The title of the question does not match the question you have asked with the code. However, I will try to deal with both. ;)


    How to print only text in a string?

    You could simply print each element in the string(i.e. char s) if it is an alphabet while iterating through it. The checking can be done using the standard function called std::isalpha, from the header <cctype>. (See live example here)

    #include <iostream>
    #include <string>
    #include <cctype> // std::isalpha
    
    int main()
    {
        std::string text = "abc123";
    
        for(const char character : text)
            if (std::isalpha(static_cast<unsigned char>(character)))
                std::cout << character;
    }
    

    Output:

    abc
    

    How to identify string is containing only number?

    Provide a function which checks for all the characters in the string whether they are digits. You can use, standard algorithm std::all_of (needs header <algorithm> to be included) along with std::isdigit (from <cctype> header) for this. (See live example online)

    #include <iostream>
    #include <string>
    #include <algorithm> // std::all_of
    #include <cctype>    // std::isdigit
    #include <iterator>  // std::cbegin, std::cend()
    
    bool contains_only_numbers(const std::string& str)
    {
        return std::all_of(std::cbegin(str), std::cend(str),
            [](char charector) {return std::isdigit(static_cast<unsigned char>(charector)); });
    }
    
    int main()
    {
        std::string text = "abc123";
        if (contains_only_numbers(text))
            std::cout << "String contains only numbers\n";
        else 
            std::cout << "String contains non-numbers as well\n";
    }
    

    Output:

    String contains non-numbers as well