搜索字符串(只查找完全匹配的字符串,不忽略大写或小写字符

Searching string (only finds exact matches does not ignore capital or small character

本文关键字:字符串 字符 查找 搜索      更新时间:2023-10-16

下面的代码从字符串中搜索名称,用户输入了7个名称,然后程序要求用户输入名称,然后从数组中执行搜索并输出名称的位置。如果用户按下n,程序将停止询问用户,否则它将继续要求用户进行搜索。此程序运行良好,但只找到完全匹配的程序。程序应该忽略大写字母和小写字母,但不能忽略。例如,数组包含名称"詹姆斯",我搜索詹姆斯,它不会给我位置。这是我下面的程序,请帮助如何做到这一点。感谢

#include <iostream>
#include <string>
using namespace std;

int main(){
string str[7];
string search;
for(int i=0; i<7; i++){
    cin>>str[i];
}

//searching the string
cout<<endl;

char option;
do{
    cout<<"Enter the name to search"<<endl;
    cin>>search;
        for(int i=0; i<7; i++){
            if(str[i]==search){
                cout<<search<<" has been found in the "<<i+1<<" Position"<<endl;
            }
        }
cout<<"Do you want to search another name, press y to continue or n to just quit"<<endl;
cin>>option;

}while(option!='n');

return 0;
}

您还没有添加忽略大小写(大写或小写)的逻辑,为此,您需要将输入字符串和存储的字符串转换为全大写或全小写,然后进行比较。

一个可以将字符串转换为大写的简单片段是:

for(int i = 0; i < strlen(s); i++)
   s[i] = toupper(s[i]);

(更好的方法是在输入时将字符串转换为大写,这样当用户输入要搜索的值时,您只需要将该值转换为大写)

为不区分大小写的字符串比较创建自己的函数:

// You must include <cctype> to use std::toupper
bool ci_compare(std::string const & s1, std::string const & s2)
{
    // If both strings have different lengths, then they
    // are different. End of the story.
    if (s1.size() != s2.size()) return false;
    // Asserting that two strings are case-insensitively equal
    // is the same as asserting that the result of converting
    // both strings to uppercase are (case-sensitively) equal.
    auto i1 = s.begin(), i2 = s2.begin(), e = s1.end();
    while (i1 != e)
      if (std::toupper(*i1++) != std::toupper(*i2++))
        return false;
    return true;
}

然后,在您发布的片段中,替换

if (str[i] == search) {

带有

if (ci_compare(str[i], search)) {