C++ 如何解析字符串并突出C++;
我想比较两个字符串,例如“1001”和“1010”。我想比较一下,然后打印一张输出图,用新的颜色或不同的字体突出显示差异。我已经检查了ASCII转义字符库。因此,我可以对输出进行着色,但我只希望在输出中突出显示差异C++ 如何解析字符串并突出C++;,c++,C++,我想比较两个字符串,例如“1001”和“1010”。我想比较一下,然后打印一张输出图,用新的颜色或不同的字体突出显示差异。我已经检查了ASCII转义字符库。因此,我可以对输出进行着色,但我只希望在输出中突出显示差异 #include <iostream> #define RESET "\033[0m" #define GREEN "\033[32m" #define UNDER "\033[4m" using namespace std; string str_1 = "
#include <iostream>
#define RESET "\033[0m"
#define GREEN "\033[32m"
#define UNDER "\033[4m"
using namespace std;
string str_1 = "0110000110";
string str_2 = "0100101001";
string str_Dif = "";
int main(){
int i = 0;
int dif = 0;
for (i = 0; i < str_1.size(); i++){
if (str_1[i] != str_2[i]){
str_2[i] = "\033[32m";
str_Dif += str_2[i];
dif++;
}
else{
str_Dif += str_2[i];
}
}
std::cout << str_1 + "\n";
std::cout << str_2 + "\n";
std::cout << UNDER << GREEN << str_Dif << RESET << std::endl;
std::cout<< "The differences: " + to_string(dif) + "\n";
return 0;
}
#包括
#定义重置“\033[0m”
#定义绿色“\033[32m”
#在“\033[4m”下定义
使用名称空间std;
字符串str_1=“0110000110”;
字符串str_2=“0101001”;
字符串str_Dif=“”;
int main(){
int i=0;
int-dif=0;
对于(i=0;i std::cout您可以使用以下命令:
std::pair<std::string, std::size_t>
highlight_diff(const std::string& ref, const std::string& s)
{
std::string res;
std::size_t count = 0;
auto it_ref = ref.cbegin();
auto it = s.cbegin();
while (it_ref != ref.cend() && it != s.cend()) {
auto p = std::mismatch(it_ref, ref.cend(), it, s.end());
res.insert(res.end(), it_ref, p.first);
std::tie(it_ref, it) = p;
p = std::mismatch(it_ref, ref.cend(), it, s.end(), std::not_equal_to<>{});
if (p.first != it_ref) {
count += p.first - it_ref;
res += GREEN;
res.insert(res.end(), it_ref, p.first);
res += RESET;
}
std::tie(it_ref, it) = p;
}
if (it != s.end()) {
count += s.end() - it;
res += GREEN;
res.insert(res.end(), it, s.end());
res += RESET;
}
return {res, count};
}
std::pair
突出显示差异(常量标准::字符串和参考,常量标准::字符串和参考)
{
std::string res;
标准::大小\u t计数=0;
自动it_ref=ref.cbegin();
自动it=s.cbegin();
而(it_ref!=ref.cend()&&it!=s.cend()){
自动p=std::不匹配(it_ref,ref.cend(),it,s.end());
res.insert(res.end(),it_ref,p.first);
标准:领带(it_ref,it)=p;
p=std::不匹配(it_ref,ref.cend(),it,s.end(),std::不等于{});
如果(p.first!=it\u ref){
计数+=p.first-it_ref;
res+=绿色;
res.insert(res.end(),it_ref,p.first);
res+=重置;
}
标准:领带(it_ref,it)=p;
}
如果(it!=s.end()){
count+=s.end()-it;
res+=绿色;
res.insert(res.end(),it,s.end());
res+=重置;
}
返回{res,count};
}
你没有说过你的代码。它不起作用吗?你在哪里看到问题?我不清楚你需要帮助的地方。
str_2[i]=“033[32m”
不起作用。从“const char*”到“char”的转换无效
。你可以使用const char*color=GREEN;str_2[i]=*color;
如果这是唯一的问题,那么这个主题只是一个分散注意力的话题。请先提取一个。作为一个新用户,也要确保你拿着这个并阅读。顺便说一句:没有理由在这里使用#define
!