在 c++ 中查找传入字符串(包括 ° 等特殊字符)中的模式
Find a pattern in incoming string(including special characters like °) in c++
我在cpp中有一个要求,我们需要在传入字符串中搜索一些模式,并需要替换为相应的值。棘手的部分是传入字符串可以包含特殊字符(如°等),模式可以是单个字符或一组字符。最初想在Map中存储模式字符串和替换值,但我遇到了特殊字符的问题,请告诉我解决这个问题的正确方法。
示例:°需要替换为"度"
int main(){
map<string,string> tempMap;
pair<string,string> tempPair;
tempMap.insert(pair<string,string>("°","degrees"));
tempMap.insert(pair<string,string>("one","two"));
tempMap.insert(pair<string,string>("three","four"));
typedef map<string,string>::iterator it_type;
string temp="abc°def";
for(it_type iterator = tempMap.begin(); iterator != tempMap.end(); iterator++)
{
//cout << iterator->first << " " << iterator->second << endl;
string::size_type found=temp.find(iterator->first);
if (found!=string::npos)
{
temp.replace(found,1,iterator->second);
cout << endl <<"after replacement " << temp;
}
}
}
输出:更换abcdegres后�def
在得到特殊字符的输出中,这是因为特殊字符°占用了2个字节。
使用宽字符支持(wstring
、wcout
和前缀为L
的字符串文字):
#include <map>
#include <string>
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
map<wstring,wstring> tempMap;
pair<wstring,wstring> tempPair;
tempMap.insert(pair<wstring,wstring>(L"°", L"degrees"));
tempMap.insert(pair<wstring,wstring>(L"one", L"two"));
tempMap.insert(pair<wstring,wstring>(L"three", L"four"));
typedef map<wstring,wstring>::iterator it_type;
wstring temp = L"abc°def";
for(it_type iterator = tempMap.begin(); iterator != tempMap.end(); iterator++) {
wstring::size_type found = temp.find(iterator->first);
if (found != wstring::npos) {
temp.replace(found, 1, iterator->second);
wcout << "after replacement " << temp << endl;
}
}
}
相关文章:
- 如何用转义符替换字符串中的所有特殊字符
- 转换特殊字符(UTF-8)
- 反转字符串中单词的位置,而不更改 O(1) 空格限制中特殊字符的顺序
- 如何在C++中打印此"█"特殊字符?
- c++为什么ifstream get()函数返回无法识别的特殊字符
- 如何检查字符串是否包含所有这些:数字、字母和特殊字符
- 转义std::字符串中的特殊字符
- SDL2加载具有特殊字符的文件
- 将 std::string 转换为具有特殊字符的 FString (TCHAR / wstring)
- 如何从文本文件C++读取整数和特殊字符
- USB序列号显示特殊字符
- 键入特殊字符并保存在文件中
- 回文,不包括特殊字符和空格
- 无法使用 Unicode 特殊字符设置窗口文本
- 使用 libmysql 插入特殊字符
- 使用具有特殊字符的正则表达式标记 C++ 字符串
- 如何输入以特殊字符开头的字符串
- 如何使用正则表达式匹配不包含特殊字符(&、\、<、>、|、)的字符串,除非它们以反斜杠开头
- 增强特殊字符的正则表达式模式
- 在 c++ 中查找传入字符串(包括 ° 等特殊字符)中的模式