【问题标题】:string uppercase function in c++C++中的字符串大写函数
【发布时间】:2014-01-21 12:44:28
【问题描述】:

我需要在 c++ 中完成 2 个基本功能

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

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

如果输入是首字母大写的字符串,第一个返回true 当所有字符串都是大写时,第二个为真 请帮助我,我是 C++ 的菜鸟

【问题讨论】:

标签: c++ string function


【解决方案1】:

使用标头 cctype,这应该可以工作。

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

编辑:

由于您还想检查仅存储字母字符的字符串,您可以使用cctype 中的isalpha 进行检查。

【讨论】:

  • 谢谢,没关系,但是我需要的条件是名称仅包含正常的名称字符,例如 a-z A-Z
【解决方案2】:

关系运算符== 是为C++ 类std::string 定义的。最好的 touppercase 实现似乎来自 Boost String Algorithms 库(参见here),所以我将在我的示例中使用它。这样的事情应该可以工作:

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

【讨论】:

    【解决方案3】:

    您的问题没有完全说明。非字母字符应该被视为小写还是大写?如果它们应该被视为大写,您可以使用:

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

    另一方面,如果非字母字符应被视为小写:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-24
      • 2020-01-04
      • 2020-02-25
      • 1970-01-01
      • 2011-06-23
      相关资源
      最近更新 更多