gpt4 book ai didi

c++ - 替换字符串中的单词,但忽略引号中的单词

转载 作者:行者123 更新时间:2023-12-01 19:36:27 26 4
gpt4 key购买 nike

我用这个循环替换字符串content中的单词:

std::string content = "This is original. \"This is original\"";

while (content.find("original") != std::string::npos)
content.replace(content.find("original"), 8, "replacement");

有没有一种简单的方法可以在“original”内部引号时不将“original”替换为“replacement”?

例如。

This is original. "This is original"

将替换为:

This is replacement. "This is original"

而不是关闭:

This is replacement. "This is replacement"

最佳答案

这个想法是搜索最先出现的内容,要替换的单词或开头引号。

如果是开盘报价,则搜索收盘报价并在其后继续替换。

std::string::find 允许您指定搜索的起始位置。

结果可能看起来像这样:

#include <iostream>
#include <string>

std::string& replace_except_in_quotes(std::string& content, const std::string& original, const std::string& replacement)
{
for(size_t pos = 0U; pos < content.size(); /*incremented in body*/)
{
size_t nextOriginal = content.find(original, pos);
if(nextOriginal == std::string::npos)
{
break;// All occurences replaced
}
size_t nextQuote = content.find('\"', pos);
bool skipQuotes = (nextQuote != std::string::npos) && (nextQuote < nextOriginal);
if(skipQuotes)
{
nextQuote = content.find('\"', nextQuote + 1);
if(nextQuote == std::string::npos)
{
break; // Missing closing quote
}
pos = nextQuote+1;
continue;
}

// Actually replace original with replacement
content.replace(nextOriginal, original.size(), replacement);
pos += replacement.size() + 1;
}
return content;
}



int main()
{
using namespace std;

string content = "this is original.\"this is original\"";
cout << replace_except_in_quotes(content, "original", "replacement") << "\n\n";

content += '\n' + content + '\n' + content + '\n' + content;
cout << replace_except_in_quotes(content, "original", "replacement") << "\n\n";;
return 0;
}

输出:

this is replacement."this is original"

this is replacement."this is original"
this is replacement."this is original"
this is replacement."this is original"
this is replacement."this is original"

神箭:https://gcc.godbolt.org/z/oYq3sy

关于c++ - 替换字符串中的单词,但忽略引号中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59860347/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com