[英]Why can't I initialize a typedef struct string or char as normally?
[英]why can't i replace char on a string like this?
我正在尝试替换以下地图中的字符: const map<char, vector<char>> ass
,请注意我有此字符串pas
,我想将所有(地图值)vector char替换为对应的地图键,我尝试了用这样的for循环迭代地图:(我从另一个关于stackoverflow的问题获得了这段代码)
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个字符的char数组
#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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.