1

我真的很想在这方面得到一些帮助。我对 C++ 编程比较陌生。我需要我的代码能够处理 ASCII 和 Unicode。以下是输入 szTestString1,在输入中找到“Ni”并将其替换为“NI”。szTestString1 是 ASCII 所以我的代码工作正常。如何使代码也能够处理 szTestString2?我用 wstring 替换了字符串,用 L"Ni" 替换了 "Ni"。此外,我使用 wcout 而不是 cout,但输出没有多大意义。而我现在迷路了。任何提示将不胜感激。

#include <iostream>
#include <string> using namespace std;

class MyClass {

public: int getNiCount(string s1) {     int Ni_counter=0;   int found,pos;

        for (pos=0; found!=-1; pos+=(found+2)){             found=s1.find("Ni",pos);
            Ni_counter++;       }

return(Ni_counter-1); }


string replaceNiWithNI(string s1) {     int found,pos;

        do{             found=s1.find("Ni",pos);            if (found!=-1)          s1.replace(found, sizeof("Ni")-1, "NI");        }while (found!=-1); return(s1); }

} obj1;



int main()

{

    const char *szTestString1 = "Ni ll Ni ll Ni nI NI nI Ni Ni";    const wchar_t *szTestString2 = L"Ni ll Ni ll Ni nI NI nI Ni Ni";

    int Ni_occur_number;    string new_string;

    // Invoke getNiCount(...) of class MyClass  Ni_occur_number=obj1.getNiCount(szTestString1);     // Invoke replaceNiWithNI(...) of class MyClass     new_string=obj1.replaceNiWithNI(szTestString1);

    // Display on screen: "Found X occurrences of Ni. New string: Y"    cout << "Found " << Ni_occur_number << " occurrences of Ni. " << "New string: " << new_string << endl;



}
4

0 回答 0