我已经研究这段代码很长一段时间了,我找不到如何使这个大小写变得不敏感
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int findCountry(string arr[], int len, string seek)
{
for (int i = 0; i < len; ++i)
{
if (arr[i] == seek) return i;
}
return -1;
}
int main(){
string countries[5]={"Brunei", "Cambodia", "East Timor", "Indonesia", "Laos"};
string capitals[5]={"Bandar Seri Begawan", "Phnom Penh", "Dili", "Jakarta", "Vientiane"};
string country;
cout << "Country: ";
cin >> country;
int index = findCountry(countries,5,country);
if (index >= 0)
cout << "Capital: " << capitals[index];
else
cout << country << " is not a South East Asian Country";
return 0;
}输出
Country: bRunEi
bRunEi is not a South East Asian Country预期产出
Country: bRunEi
Capital: Bandar Seri Begawan我被指示使用cstring头,但这是我唯一能猜到的事情,任何帮助都会感谢ps:对不起,英语不好。
发布于 2022-05-02 13:41:09
有几点改进可以简化您的代码。
首先,如果您使用标准集装箱为您的国家。
std::vector<std::string> countries = {"Brunei", "Cambodia", "East Timor", "Indonesia", "Laos"};对于不区分大小写的输入,可以使用https://en.cppreference.com/w/cpp/string/byte/tolower或其同级触摸器进行转换。
std:收费器在<cctype>头中,但我认为这是<cstring>的一部分。
引用包含一个涵盖大小写的用法示例。
std::string str_tolower(std::string s) {
std::transform(s.begin(), s.end(), s.begin(),
[](unsigned char c){ return std::tolower(c); }
);
return s;
}转换在标题中,您应该查看其中的许多简单算法,这些算法允许您以比在findCountry中使用常规的for -循环更简单的方式来描述代码。例如,查看algoritm::find。
表达式unsigned char c{ .}是一个lambda表达式,与算法结合在一起非常有用。https://en.cppreference.com/w/cpp/language/lambda
发布于 2022-05-02 13:43:44
关于大小写不敏感比较的:
您可以使用下面的函数IsEqualStringsCaseInsensitive来比较忽略大小写的两个字符串。您可以调用它,而不是使用(arr[i] == seek)来比较字符串。
#include <string>
#include <cctype>
bool IsEqualStringsCaseInsensitive(std::string const & s1, std::string const & s2)
{
size_t len1 = s1.length();
size_t len2 = s2.length();
if (len1 != len2) {
return false;
}
for (size_t i = 0; i < len1; ++i) {
if (isascii(s1[i]) && isascii(s2[i])) {
// Both are ASCII - compare lower case version:
if (std::tolower(s1[i]) != std::tolower(s2[i])) {
return false;
}
}
else {
// Compare as-is:
if (s1[i] != s2[i]) {
return false;
}
}
}
return true;
}关于您的代码的一些附加说明:
一般来说,最好使用(string arr[]).
using namespace std --参见这里Why is "using namespace std;" considered bad practice?.
const&传递seek以避免复制。UPDATE:基于@EvilTeach下面的注释( std::tolower只对ASCII字符有效),我修改了上面的代码。现在,它只在两个字符都是std::tolower的情况下才调用ASCII。否则将比较为-is(区分大小写没有任何意义,至少对其中一个没有意义,这意味着对于字符串相等,它们必须是相同的)。
https://stackoverflow.com/questions/72087458
复制相似问题