c++ string wstring 字符串替换

本文介绍了一个用于C++中字符串替换的实用函数。该函数能够将std::wstring中的指定子串替换成另一个字符串,适用于需要频繁进行字符串操作的场景。

c++的string本身没有字符串替换为另外一个字符串的功能,特此在这里添加一个替换函数

int CStringTool::Replace(std::wstring& strContent, std::wstring& strReplace, std::wstring & strDest)
{

	while (true)
	{
		size_t pos = strContent.find(strReplace);
		if (pos != std::wstring::npos)
		{
			WCHAR pBuf[1]={L'\0'};
			strContent.replace(pos, strReplace.length(), pBuf, 0);
			strContent.insert(pos, strDest);
		}
		else
		{
			break;
		}
	}

	return 0;
}


 

### C++ 中 `std::wstring` 字符串比较的方法 在 C++ 标准库中,`std::wstring` 是一种专门用于处理宽字符(`wchar_t` 类型)的字符串类。其提供了类似于 `std::string` 的操作接口,因此可以使用相同的比较运算符来完成字符串之间的比较。 以下是关于 `std::wstring` 比较的具体实现方式及其示例代码: #### 使用关系运算符进行比较 可以直接利用 C++ 提供的关系运算符 (`==`, `<`, `>`, `<=`, `>=`) 对两个 `std::wstring` 对象进行比较。这些运算符基于字典序规则逐字符对比宽字符的内容。 ```cpp #include <iostream> #include <locale> #include <string> int main() { std::locale loc(std::locale(), new std::codecvt_utf8<wchar_t>); // 设置 UTF-8 转换支持 std::wcout.imbue(loc); std::wstring str1 = L"你好"; std::wstring str2 = L"世界"; if (str1 == str2) { std::wcout << L"str1 和 str2 相同\n"; } else if (str1 < str2) { std::wcout << L"str1 小于 str2\n"; } else { std::wcout << L"str1 大于 str2\n"; } return 0; } ``` 上述代码展示了如何通过简单的条件语句判断两段 Unicode 文本是否相等或者按照字典顺序排列的情况[^2]。 #### 利用成员函数 compare() 除了直接运用运算符外,还可以调用 `std::wstring` 的成员函数 `compare()` 来执行更复杂的比较逻辑。此方法允许指定要参与比较的部分子串范围以及忽略大小写等因素的影响。 下面给出一段示范程序说明如何应用该技术: ```cpp #include <iostream> #include <locale> #include <string> bool caseInsensitiveCompare(const std::wstring& s1, const std::wstring& s2){ auto it1 = s1.begin(); auto end1= s1.end(); auto it2 = s2.begin(); while(it1 !=end1 && *it1 ==*it2 ){ ++it1;++it2 ; } return !(it1!=end1 || *(--it2)!=*(--it1)); } int main(){ std::locale loc(std::locale(),new std::codecvt_utf8<wchar_t>); std::wcout.imbue(loc); std::wstring ws1=L"HELLO"; std::wstring ws2=L"hello"; int result =ws1.compare(ws2); if(result ==0){ std::wcout<<L"The strings are identical.\n"; }else{ std::wcout<<((result<0)?L"'HELLO' precedes 'hello'\n":L"'HELLO' follows 'hello'\n"); } bool ciResult=caseInsensitiveCompare(ws1,ws2); if(ciResult){ std::wcout<<L"The strings match when ignoring case differences.\n"; }else{ std::wcout<<L"The strings do not match even with case insensitivity applied.\n"; } return 0; } ``` 这里不仅演示了基本的 `compare()` 方法,还额外提供了一个自定义辅助功能——不区分大小写的版本检查[^3]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

北京橙溪 www.enwing.com

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值