简体   繁体   中英

string uppercase function in c++

I need to do 2 basic functions in c++

bool validMeno(const string& text){
    if ()
    return DUMMY_BOOL;
}

bool validPriezvisko(const string& text){
    return DUMMY_BOOL;
}

first one returns true if the input is string with first letter uppercase second one is true when all string is uppercase plese help me i am noob in c++

Use header cctype and this should work.

bool validMeno(const string& text){
    if (text.size() == 0)
        return false;

    return isupper(text[0]);
}

bool validPriezvisko(const string& text){
    if (text.size() == 0)
        return false;

    for (std::string::size_type i=0; i<text.size(); ++i)
    {
        if (islower(text[i]))
            return false;
    }

    return true;
}

EDIT:

Since you also want to check for strings that only stores alphabetic characters, you can use isalpha from cctype to check for that.

The relational operator == is defined for the C++ class std::string . The best touppercase implementation seems to come from the Boost String Algorithms library (see here ), so I'll use that in my example. Something like this should work:

#include <boost/algorithm/string.hpp>
#include <string>

bool first_n_upper(const std::string & text, size_t n)
{
    if (text.empty())
        return false;

    std::string upper = boost::to_upper_copy(text);
    return text.substr(0, n) == upper.substr(0, n);
}

bool validMeno(const std::string & text)
{
    return first_n_upper(text, 1);
}

bool validPriezvisko(const std::string & text)
{
    return first_n_upper(text, std::string::npos);
}

Your problem is not completely specified. Should non-alpha characters be treated as lower-case or upper case? If they should be considered uppercase you could use:

#include <string>
#include <algorithm>

using namespace std;

bool validMeno(const string& text) {
    return !text.empty() && isupper(text[0]);
}

bool validPriezvisko(const string& text) {
    return !any_of(begin(text), end(text), islower);
}

On the other hand if non-alpha characters should be considered lower-case:

#include <string>
#include <algorithm>

using namespace std;

bool validMeno(const string& text) {
    return !text.empty() && !islower(text[0]);
}

bool validPriezvisko(const string& text) {
    return all_of(begin(text), end(text), isupper);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM