【发布时间】: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次。
标签: c++ string algorithm performance loops