比较用户的字符串

Compare string from the user

本文关键字:字符串 用户 比较      更新时间:2023-10-16

我正在尝试从链接列表中删除一个节点。节点具有用户输入的名称。但是我无法弄清楚如何在循环时忽略大写/小写。这是我的代码。

void del(string e)
{
    temp=new node;
    temp=head;
    temp2=new node;
    temp2=temp->next;
    if(temp->info==e)
    {
        head=temp->next;
        delete temp;
    }
    else
    {
        while(temp2->info!=e)
        {
            temp=temp->next;
            temp2=temp2->next;
        }
        temp2=temp2->next;
        temp->next=temp2;
    }
}

我得到了这个

的字符串
cout<<"Enter the name to delete"<<endl;
ws(cin);
getline(cin,e);
del(e);

因此,有什么办法可以忽略大写/小写字母,而循环和if语句?

两个字符串的敏感比较的窍门是将两个字符串转换为较低或上情况,然后比较。

不幸的是,STL不能为案例转换提供非常方便的方法。因此,这里有一些可能性:https://stackoverflow.com/a/313990/1143850。只是从那里复制:

#include <algorithm>
#include <string> 
std::string data = "Abc"; 
std::transform(data.begin(), data.end(), data.begin(), ::tolower);

所以,在您的情况下,

 string lowerE = std::transform(e.begin(), e.end(), e.begin(), ::tolower);    
 ...
 while(std::transform(temp2->info.begin(), temp2->info.end(), temp2->info.begin(), ::tolower) != lowerE) ...

当然,您可以创建一个函数来简化它或在那里使用其他转换方法。

,另一种可能性肯定是创建您自己的比较功能,并使用 tolowertowlower函数来比较char。

您无需手动转换被转换的字符串的情况。如果您要处理字符串,请使用strcmp。对于情况不敏感的检查,您可以使用_strcmpi。

,例如

if(!strcmp(String1, String2)) { .... }

如果strcmp返回0(fals),则有一个匹配,并应用了案例灵敏度。

对于没有情况敏感性的比较,您使用_strcmpi。

,例如

#include <Windows.h>
#include <iostream>
using namespace std;
BOOL StringMatch(
    CONST CHAR *CmpString,
    CONST CHAR *CmpString2
)
{
    return (!_strcmpi(CmpString,
        CmpString2)) ? TRUE : FALSE;
}
int main()
{
    if (StringMatch("hello", "HELLO"))
    {
        cout << "Match without case sensitivityn";
    }
    getchar();
    return 0;
}

由于您使用的是std :: string,因此可以使用.c_str()。

,例如

string hellostring = "hello";
if (StringMatch(hellostring.c_str(), "HELLO"))
{
    cout << "Match without case sensitivityn";
}

如果您需要切换到Unicode编码而不是ASCII,则有WCSCMP和_WCS*/WCS*。