【问题标题】:How can I shorten multiple conditions of checking substring existence?如何缩短检查子字符串存在的多个条件?
【发布时间】:2015-10-08 16:12:27
【问题描述】:

我有这段代码正在运行(s 这里是一个结构变量):

// Convert char array to string
string name(s.name);
string surname(s.surname);
string username(s.username);

// Convert string to lower case
transform(name.begin(), name.end(), name.begin(), ::tolower);
transform(surname.begin(), surname.end(), surname.begin(), ::tolower);
transform(username.begin(), username.end(), username.begin(), ::tolower);

// Check if keyword is a substring inside above string
string::size_type pos = name.find(keyword);
string::size_type pos2 = surname.find(keyword);
string::size_type pos3 = username.find(keyword);
if(pos != string::npos || pos2 != string::npos || pos3 != string::npos) {
    cout << "Found";
}

有人可以给我一些建议如何缩短上面的代码(我已经尝试过使用循环,但结果是一团糟并且没有运行)。由于我是 C++ 新手,请多多包涵。

【问题讨论】:

  • 由于代码正确,codereview.stackexchange.com 似乎更合适。
  • 这段代码最大的问题是“CARL FRIEDRICH GAUSS”会失败。更重要的是,它基本上只适用于英语,这是少数在小写和大写之间具有 1:1 映射的拉丁字母语言之一。
  • 写一个函数,调用3次。
  • 当性能很重要并且您已经知道不会有多少字符是大写时,使用foreach 并事先检查isupper 可能会更快。

标签: c++ string algorithm performance loops


【解决方案1】:
string name(s.name);
name.push_back('\0'); 
name+=s.surname;
name.push_back('\0');
name+=s.username;

transform(name.begin(), name.end(), name.begin(), ::tolower);
string::size_type pos = name.find(keyword);

if(pos != string::npos ) {
    cout << "Found";
}

【讨论】:

    【解决方案2】:

    你可以试试这样的:

    bool contains(const S& s, const std::string& keyword)
    {
        // Convert char array to string
        std::string names[3] = {s.name, s.surname, s.username};
    
        for (auto& name : names) {
            // Convert string to lower case
            transform(name.begin(), name.end(), name.begin(), ::tolower);
    
            // Check if keyword is a substring inside above string
            string::size_type pos = name.find(keyword);
            if(pos != string::npos) {
                std::cout << "Found";
                return true;
            }
        }
        return false;
    }
    

    【讨论】:

    • 假设他需要添加middle_name。 Bo Persson 是对的,他需要编写一个函数并调用它 3 次。
    猜你喜欢
    • 2015-11-18
    • 2020-04-04
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 2021-06-18
    • 2021-03-08
    • 1970-01-01
    • 2014-11-14
    相关资源
    最近更新 更多