为什么我不能替换这样的字符串上的字符?



我正在尝试替换以下映射中的字符:const map<char, vector<char>> ass,请注意,我pas有这个字符串,我想将所有(地图值(向量字符替换为相应的映射键,我尝试使用如下所示的 for 循环迭代映射: (我从堆栈溢出的另一个问题中得到了这段代码(

for (auto const &ent1 : ass) {
//ent1.first = first key
//ent1.second = second key
}

所以我尝试像这样迭代地图值向量:

string char1;
string char2;
string wr;
for (auto const &ent1 : ass) {
for (int i = 0; i < ent1.second.size(); i++) {
specialValues += ent1.second[i];
char2 = ent1.second[i];
char1 = ent1.first;
regex e("([" + char1 + "])");
cout << ("([" + char1 + "])");
cout << char2;
wr = regex_replace("c1a0", e, char2);
}
}

所以我希望字符串"c1a0"在循环后变成"ciao",但它只是没有改变任何东西,

我也试过:

wr = regex_replace("c1a0", e, "o");

输出 : C1A0

regex e("([0])");
wr = regex_replace("c1a0", e, char2);

输出 : C1A2

我不知道,这对我来说毫无意义。我不明白,你能帮我找出我的代码中出了什么问题吗?

当然,如果我写:

regex e("([0])");
wr = regex_replace("c1a0", e, "o");

它给了我"c1ao",这就是我想要的。

以下代码对我有用:

#include <string>
#include <map>
#include <regex>
#include <iostream>
using namespace std;
int main() {
const map<char, vector<char>> ass = {
{ '1', {'i'} },
{ '0', {'o'} },
};
string char1;
string char2;
string wr = "c1a0";
for (auto const &ent1 : ass) {
for (int i = 0; i < ent1.second.size(); i++) {
//specialValues += ent1.second[i];
char2 = ent1.second[i];
char1 = ent1.first;
regex e("([" + char1 + "])");
cout << ("([" + char1 + "])") << std::endl;
cout << char2<< std::endl;
wr = regex_replace(wr, e, char2);
cout << wr << std::endl;
}
}
}

但恕我直言,这里的正则表达式矫枉过正。您可以手动迭代字符串并替换字符,如以下代码片段所示:

#include <string>
#include <set>
#include <iostream>
#include <vector>
using namespace std;
struct replace_entry {
char with;
std::set<char> what;
};
int main() {
const std::vector<replace_entry> replaceTable = {
{ 'i', {'1'} },
{ 'o', {'0'} },
};
string input = "c1a0";
for (auto const &replaceItem : replaceTable) {
for (char& c: input ) {
if(replaceItem.what.end() != replaceItem.what.find(c)) {
c = replaceItem.with;
}
}
}
cout << input << std::endl;
}

另一种方法是创建 256 个元素的字符数组

#include <string>
#include <iostream>
class ReplaceTable {
private:
char replaceTable_[256];
public:
constexpr ReplaceTable() noexcept 
: replaceTable_()
{
replaceTable_['0'] = 'o';
replaceTable_['1'] = 'i';
}
constexpr char operator[](char what) const noexcept {
return replaceTable_[what];
}
};
// One time initialization
ReplaceTable g_ReplaceTable;
int main() {
std::string input = "c1a0";
// Main loop
for (char& c: input ) {
if(0 != g_ReplaceTable[c] ) c = g_ReplaceTable[c];
}
std::cout << input << std::endl;
}

最新更新