版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/infoworld/article/details/79217550
场景
1.C/C++开发过程中, C字符串函数或者std::string是相当实用的了, 可以查询,截取,移除等, 但是一般都是移除指定的一个字符而不是字符串, 移除还是大小写敏感的. 当然也可以用正则表达式来移除或查询,
但是总也得3-4行代码吧.
2.std::string 不但可以存储字符串, 还可以存储任意字节数据. 但是在查询,替换,移除字符串上也是和C差不多,
如果要在一段文本里查询某个姓名是否存在,那么就得把这个文本先转换为大写, 之后再把要查询的姓名转换为大写, 之后再查询, 相当麻烦.
说明
1.Windows Desktop编程里的Shell库里就有相关的字符串处理函数, 可以说是对C/C++字符串不足的补充, 非常实用, 比如大小写不敏感的查询,移除前后空格, 把数值转换为容量字符串, 大小写不敏感的字符串比较.
2.这里摘取了部分常用的路径处理函数, 还有其他函数请参考Shell String Handling Functions.
代码
#include "Shlwapi.h"
void TestShellStringFunction()
{
// ChrCmpI
std::cout << "============= 比较两个字符串,大小写不敏感, 而strcmp是大小写敏感的 =============" << std::endl;
auto Tom = L"Tom";
auto tom = L"tom";
auto Ton = L"ToN";
if(StrCmpI(Tom,tom) == 0)
std::wcout << Tom << " and " << tom << L" is same." << std::endl;
if(StrCmpI(Tom,Ton) < 0)
std::wcout << Tom << " smaller than " << Ton << std::endl;
// StrStrI
std::cout << "============= 查询子字符串是否存在,大小写不敏感,而strstr是大小写敏感的 =============" << std::endl;
// 常用在搜索框查询处理,比较实用,这样就不需要把原字符串和子字符串转换为大写再去搜索.
auto text = L"I am a cloud, I am a AI, Configuration for you. thank you.";
auto sub = L"ai";
if(StrStrI(text,sub))
std::wcout << text << " has substring " << sub << std::endl;
std::cout << "============= 移除字符串前后指定字符,比如空格和tab =============" << std::endl;
// 这个应该是Win最快的做法, 不需要自己写函数来移除前后空格了.
wchar_t article[256] = L" hello world. ";
wchar_t trim[] = {32,9,L'\0'};
StrTrim(article,trim);
std::wcout << L"|" <<article << L"|" << std::endl;
// StrFormatByteSizeW
std::cout << "============= 把数值转换为容量大小字符串,也不需要自己去写了,省事. =============" << std::endl;
// 使用系统的函数,可以避免当前系统基数是以1000还是1024来识别的了.
if(StrFormatByteSizeW(21341231234,article,256))
std::wcout << L"size is:" << article << std::endl;
}
输出:
============= 比较两个字符串,大小写不敏感, 而strcmp是大小写敏感的 =============
Tom and tom is same.
Tom smaller than ToN
============= 查询子字符串是否存在,大小写不敏感,而strstr是大小写敏感的 =========
====
I am a cloud, I am a AI, Configuration for you. thank you. has substring ai
============= 移除字符串前后指定字符,比如空格和tab =============
|hello world.|
============= 把数值转换为容量大小字符串,也不需要自己去写了,省事. ============
=
size is:19.8 GB