将 N 个公式替换为一个(字符串插值)

Replace N formulas to one (string interpolation)

本文关键字:字符串 插值 一个 替换      更新时间:2023-10-16
是否可以

在 c++ 中进行这样的字符串转换:

例:

从:

F = a && b && c;
H = p ^ 2 + w
K = H > 10 || e < 5;
J = F && !K;

自:

J = (a && b && c) && !( (p ^ 2 + w) > 10 || e < 5);

看起来您正在请求插值。在这种情况下,当然!首先,您需要构造键和值的map<string, string>,例如:

map<string, string> interpolate = { { "F"s, "a && b && c"s }, { "H"s, "p ^ 2 + w"s }, { "K"s, "H > 10 || e < 5"s }, { "J"s, "F && !K"s } };

然后只需使用for_eachstding::findstring::replace

for(const auto& i : interpolate) for_each(begin(interpolate), end(interpolate), [&](auto& it){ for(auto pos = it.second.find(i.first); pos != string::npos; pos = it.second.find(i.first, pos)) it.second.replace(pos, i.first.size(), '(' + i.second + ')'); });

现场示例

运行此代码后,使用 for(const auto& i : interpolate) cout << i.first << " : " << i.second << endl 输出interpolate时,您将获得:

F : a && b && c
H : p ^ 2 + w
J : (a && b && c( && !((p ^ 2 + w(> 10 || e <5(
K : (p ^ 2 + w(> 10 ||e <5