搜索字符串(只查找完全匹配的字符串,不忽略大写或小写字符
Searching string (only finds exact matches does not ignore capital or small character
下面的代码从字符串中搜索名称,用户输入了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)) {
相关文章:
- 如何将一个ostringstream十六进制字符串字符对转换为单个unit8t等价的二进制值
- 尝试将字符串/字符转换为整数会产生意外结果
- 为什么没有访问所有字符串字符?
- 将子字符串字符从字符串值转换为 int,然后将其分配给 int 变量
- 如何将字符串字符与结构数组进行比较?
- 将单个字符串/字符输入串行监视器
- 读取字符串字符时出错 - 对于数组中的字符串值
- C++ C 样式字符串/字符数组的大小 - 优化
- 读取字符串字符时出错
- C++ 使用 Strtok 读取字符串字符时出错
- 如何将 int 数组的 1 个元素转换为字符串/字符
- 在另一个字符串中逐个复制字符串字符
- 将字符串字符映射到矢量
- MBED RTOS将Float转换为字符串/字符阵列
- 如何使用字符串字符数组中的 ++ 运算符访问下一个字符串
- 如何比较C++中的单个字符串字符?
- 内部字符串/字符如何在 int 和 float 中存储
- 将十六进制转换为可打印的字符串/字符
- wcscpy_s后读取字符串字符时出错
- 检查字符串字符和长度