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

时间:2015-07-01 02:28:51

标签: c++ regex string

我在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;
      }


}

}

输出:替换后abcdegrees def

在输出获取特殊字符时,这是因为特殊字符°占用2个字节。

1 个答案:

答案 0 :(得分:1)

使用广泛字符支持(wstringwcoutL - 前缀字符串文字):

#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;
        }
    }
}