0

I have a requirement in cpp where we need to search some pattern in incoming string and need to replace with corresponding values.Here comes the tricky part incoming string can contain special characters(like ° etc) and pattern can be single character or group of characters. Initially thought to store pattern string and replacement value in Map but i am facing problems with special characters please let me know the correct approach to solve this problem.

example: ° need to be replace by "degrees"

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


}

}

output : after replacement abcdegrees�def

in output getting specialcharacter, this is because special character ° occupying 2 bytes.

kalamad
  • 3
  • 2
  • you can use vector to store them and use vector push_back() to store untill input is new line character. Then you can manipulate which ever way you want. – Madhu Kumar Dadi Jul 01 '15 at 02:32
  • What problems did you encounter with patterns like the ° character that you couldn't solve? – 5gon12eder Jul 01 '15 at 02:32
  • Are you asking for someone to write the code for you? Do you have code already that isn't working? – PC Luddite Jul 01 '15 at 02:36
  • 1
    You might want to mention how the `°` and other such "special" characters are encoded: e.g. rtf-8, Unicode etc. (after which you should go find a library therefor). – Tony Delroy Jul 01 '15 at 02:46

1 Answers1

1

Use the wide character support (wstring, wcout, and the L-prefixed string literals):

#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;
        }
    }
}
dlask
  • 8,776
  • 1
  • 26
  • 30