在 c++ 中查找传入字符串(包括 ° 等特殊字符)中的模式

Find a pattern in incoming string(including special characters like °) in c++

本文关键字:特殊字符 模式 包括 查找 c++ 字符串      更新时间:2023-10-16

我在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个字节。

使用宽字符支持(wstringwcout和前缀为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;
        }
    }
}