我想用字符串替换字符串中的字符.我可以就地做吗?由于新字符串的长度大于原始字符串.问题是我可以使用额外的缓冲区吗?
例如
void replaceChar(std::string &input, std::string replacementString, char charToReplace)
{
//some code here. No additional buffer
}
void main(){
std::string input = "I am posting a comment on LinkedIn";
std::string replacementString = "pppp";
char charToReplace = 'o';
replaceChar(input, replacementString, charToReplace);
}
我只想要策略(算法).如果算法的设计保持一定的语言,一旦它被启动就不会动态增加或减少字符串长度,这将是很好的
解决方法:
std :: string有一个替换成员,但它的工作方式是数字位置,而不是字符串的先前内容.因此,您通常必须在循环中将它与find成员组合,如下所示:
std::string old("o");
int pos;
while ((pos = x.find(old)) != std::string::npos)
x.replace(pos, old.length(), "pppp");
就个人而言,我很少关注字符串调整大小的频率,但如果这是一个主要问题,你可以使用std :: count来查找旧字符串的出现次数,乘以旧字符串之间的大小差异和新字符串,并使用std :: string :: reserve()来保留足够的空间.但请注意,在C 11中添加了保留 – 较旧的实现将不具备它.
编辑:虽然它不是你所使用的字符串的问题,正如@ipc所指出的,如果替换字符串包含要替换的值的实例,这将无法正常工作.如果您需要处理它,您需要在字符串中提供开始每次搜索的偏移量:
int pos = 0;
while ((pos = x.find(old, pos)) != std::string::npos) {
x.replace(pos, old.length(), rep);
pos += rep.length();
}
或者,在这种情况下,您可能更喜欢for循环:
std::string old("o");
std::string rep("pop");
for (int pos=0;
(pos = x.find(old, pos)) != std::string::npos;
pos+=rep.length())
{
x.replace(pos, old.length(), rep);
}
标签:c,string,algorithm
来源: https://codeday.me/bug/20190729/1573779.html