百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术分析 > 正文

C++中忽略大小写的字符串比较的三种方法

liebian365 2024-11-20 18:25 61 浏览 0 评论

在C++编程语言中,字符串比较是一个常见的任务,尤其是在处理用户输入或文件内容时。然而,由于大小写差异,直接比较字符串可能会导致意外的结果。幸运的是,C++提供了几种方法来忽略大小写进行字符串比较。本文将介绍一些有效的方法,并通过示例代码展示如何实现这些方法。

方法1:使用标准比较运算符

在C++中,我们可以使用==运算符来比较两个字符串。为了忽略大小写,我们可以先将字符串转换为全小写或全大写,然后再进行比较。这种方法简单直观,适用于大多数情况。

#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>

// 函数:比较两个字符串,忽略大小写
bool compareIgnoreCase(const std::string& str1, const std::string& str2) {
    std::string lowerStr1 = str1;
    std::string lowerStr2 = str2;
    std::transform(lowerStr1.begin(), lowerStr1.end(), lowerStr1.begin(), ::tolower);
    std::transform(lowerStr2.begin(), lowerStr2.end(), lowerStr2.begin(), ::tolower);
    return lowerStr1 == lowerStr2;
}

int main() {
    std::string str1 = "Hello World!";
    std::string str2 = "hello world!";
    std::string str3 = "Hello Everyone!";

    if (compareIgnoreCase(str1, str2)) {
        std::cout << "str1 and str2 are equal (ignoring case)" << std::endl;
    } else {
        std::cout << "str1 and str2 are not equal" << std::endl;
    }

    if (compareIgnoreCase(str1, str3)) {
        std::cout << "str1 and str3 are equal (ignoring case)" << std::endl;
    } else {
        std::cout << "str1 and str3 are not equal" << std::endl;
    }

    return 0;
}

方法2:使用strncasecmp()

strncasecmp()函数是C++标准库中的一个函数,用于比较两个字符串,忽略大小写,并且只比较指定长度的字符。这个函数非常适合在已知字符串长度的情况下使用。

#include <iostream>
#include <string>
#include <cstring>

// 函数:比较两个字符串的前n个字符,忽略大小写
bool compareNCharsIgnoreCase(const std::string& str1, const std::string& str2, size_t n) {
    return strncasecmp(str1.c_str(), str2.c_str(), n) == 0;
}

int main() {
    std::string str1 = "Hello World!";
    std::string str2 = "hello world!";
    std::string str3 = "hello universe";

    if (compareNCharsIgnoreCase(str1, str2, 11)) {
        std::cout << "str1 and str2 are equal for the first 11 characters (ignoring case)" << std::endl;
    } else {
        std::cout << "str1 and str2 are not equal" << std::endl;
    }

    if (compareNCharsIgnoreCase(str1, str3, 11)) {
        std::cout << "str1 and str3 are equal for the first 11 characters (ignoring case)" << std::endl;
    } else {
        std::cout << "str1 and str3 are not equal" << std::endl;
    }

    return 0;
}

方法3:使用strcasecmp()

与strncasecmp()类似,strcasecmp()函数也用于比较两个字符串,忽略大小写。不过,它比较的是整个字符串,而不是指定长度的字符。

#include <iostream>
#include <string>
#include <cstring>

// 函数:比较两个字符串,忽略大小写
bool compareStringsIgnoreCase(const std::string& str1, const std::string& str2) {
    return strcasecmp(str1.c_str(), str2.c_str()) == 0;
}

int main() {
    std::string str1 = "Hello World!";
    std::string str2 = "hello world!";
    std::string str3 = "Hello Everyone!";

    if (compareStringsIgnoreCase(str1, str2)) {
        std::cout << "str1 and str2 are equal (ignoring case)" << std::endl;
    } else {
        std::cout << "str1 and str2 are not equal" << std::endl;
    }

    if (compareStringsIgnoreCase(str1, str3)) {
        std::cout << "str1 and str3 are equal (ignoring case)" << std::endl;
    } else {
        std::cout << "str1 and str3 are not equal" << std::endl;
    }

    return 0;
}

扩展应用

除了基本的字符串比较,我们还可以将这些方法应用于更复杂的场景,如文件内容比较、用户输入验证等。例如,我们可以编写一个程序,比较用户输入的密码是否与存储的加密密码匹配,忽略大小写。

#include <iostream>
#include <string>
#include <algorithm>

// 函数:安全比较两个字符串,忽略大小写
bool secureCompare(const std::string& input, const std::string& stored) {
    std::string inputLower = input;
    std::string storedLower = stored;
    std::transform(inputLower.begin(), inputLower.end(), inputLower.begin(), ::tolower);
    std::transform(storedLower.begin(), storedLower.end(), storedLower.begin(), ::tolower);
    return inputLower == storedLower;
}

int main() {
    std::string userInput = "Password123";
    std::string storedPassword = "password123";

    if (secureCompare(userInput, storedPassword)) {
        std::cout << "Password is correct" << std::endl;
    } else {
        std::cout << "Password is incorrect" << std::endl;
    }

    return 0;
}

结论

在C++中,有多种方法可以实现忽略大小写的字符串比较。选择哪种方法取决于具体的应用场景和需求。无论是使用标准库函数还是自定义函数,重要的是理解每种方法的工作原理和适用情况。通过这些方法,我们可以确保字符串比较的准确性和一致性,从而提高程序的健壮性和用户体验。

这些示例代码提供了一个基础,你可以根据自己的需求进行修改和扩展。在实际开发中,可能还需要考虑性能优化、安全性等因素。希望这些信息能帮助你更好地理解和应用C++中的字符串比较。


相关推荐

“版本末期”了?下周平衡补丁!国服最强5套牌!上分首选

明天,酒馆战棋就将迎来大更新,也聊了很多天战棋相关的内容了,趁此机会,给兄弟们穿插一篇构筑模式的卡组推荐!老规矩,我们先来看10职业胜率。目前10职业胜率排名与一周前基本类似,没有太多的变化。平衡补丁...

VS2017 C++ 程序报错“error C2065:“M_PI”: 未声明的标识符&quot;

首先,程序中头文件的选择,要选择头文件,在文件中是没有对M_PI的定义的。选择:项目——>”XXX属性"——>配置属性——>C/C++——>预处理器——>预处理器定义,...

东营交警实名曝光一批酒驾人员名单 88人受处罚

齐鲁网·闪电新闻5月24日讯酒后驾驶是对自己和他人生命安全极不负责的行为,为守护大家的平安出行路,东营交警一直将酒驾作为重点打击对象。5月23日,东营交警公布最新一批饮酒、醉酒名单。对以下驾驶人醉酒...

Qt界面——搭配QCustomPlot(qt platform)

这是我第一个使用QCustomPlot控件的上位机,通过串口精确的5ms发送一次数据,再将读取的数据绘制到图表中。界面方面,尝试卡片式设计,外加QSS简单的配了个色。QCustomPlot官网:Qt...

大话西游2分享赢取种族坐骑手办!PK趣闻录由你书写

老友相聚,仗剑江湖!《大话西游2》2021全民PK季4月激燃打响,各PK玩法鏖战齐开,零门槛参与热情高涨。PK季期间,不仅各种玩法奖励丰厚,参与PK趣闻录活动,投稿自己在PK季遇到的趣事,还有机会带走...

测试谷歌VS Code AI 编程插件 Gemini Code Assist

用ClaudeSonnet3.7的天气测试编码,让谷歌VSCodeAI编程插件GeminiCodeAssist自动编程。生成的文件在浏览器中的效果如下:(附源代码)VSCode...

顾爷想知道第4.5期 国服便利性到底需优化啥?

前段时间DNF国服推出了名为“阿拉德B计划”的系列改版计划,截至目前我们已经看到了两项实装。不过关于便利性上,国服似乎还有很多路要走。自从顾爷回归DNF以来,几乎每天都在跟我抱怨关于DNF里面各种各样...

掌握Visual Studio项目配置【基础篇】

1.前言VisualStudio是Windows上最常用的C++集成开发环境之一,简称VS。VS功能十分强大,对应的,其配置系统较为复杂。不管是对于初学者还是有一定开发经验的开发者来说,捋清楚VS...

还嫌LED驱动设计套路深?那就来看看这篇文章吧

随着LED在各个领域的不同应用需求,LED驱动电路也在不断进步和发展。本文从LED的特性入手,推导出适合LED的电源驱动类型,再进一步介绍各类LED驱动设计。设计必读:LED四个关键特性特性一:非线...

Visual Studio Community 2022(VS2022)安装图文方法

直接上步骤:1,首先可以下载安装一个VisualStudio安装器,叫做VisualStudioinstaller。这个安装文件很小,很快就安装完成了。2,打开VisualStudioins...

Qt添加MSVC构建套件的方法(qt添加c++11)

前言有些时候,在Windows下因为某些需求需要使用MSVC编译器对程序进行编译,假设我们安装Qt的时候又只是安装了MingW构建套件,那么此时我们该如何给现有的Qt添加一个MSVC构建套件呢?本文以...

Qt为什么站稳c++GUI的top1(qt c)

为什么现在QT越来越成为c++界面编程的第一选择,从事QT编程多年,在这之前做C++界面都是基于MFC。当时为什么会从MFC转到QT?主要原因是MFC开发界面想做得好看一些十分困难,引用第三方基于MF...

qt开发IDE应该选择VS还是qt creator

如果一个公司选择了qt来开发自己的产品,在面临IDE的选择时会出现vs或者qtcreator,选择qt的IDE需要结合产品需求、部署平台、项目定位、程序猿本身和公司战略,因为大的软件产品需要明确IDE...

Qt 5.14.2超详细安装教程,不会来打我

Qt简介Qt(官方发音[kju:t],音同cute)是一个跨平台的C++开库,主要用来开发图形用户界面(GraphicalUserInterface,GUI)程序。Qt是纯C++开...

Cygwin配置与使用(四)——VI字体和颜色的配置

简介:VI的操作模式,基本上VI可以分为三种状态,分别是命令模式(commandmode)、插入模式(Insertmode)和底行模式(lastlinemode),各模式的功能区分如下:1)...

取消回复欢迎 发表评论: