gpt4 book ai didi

c++ - 替换 vector 字符串中的字符串

转载 作者:行者123 更新时间:2023-11-28 08:08:35 25 4
gpt4 key购买 nike

我想替换 vector 字符串中的字符串。我的意思是,我有一个 vector 字符串,定义 vector tmpback ,信息如下:name_lastname_phonenumber

我想替换一些姓氏。例如,如果某人是 john_smith_5551234,我想将 smith 替换为 smith100。

这是我的代码,其中的一部分:

vector<string> tmpback = names;
for (Int_t i = 0; i < tmpback.size(); i++) {
replace(tmpback[i].begin(),tmpback[i].end(),"smith", "smith"+number);
}

(我之前将数字定义为 Int_t 数字 = 0,稍后给出一些值)。有人知道我做错了什么吗?

谢谢

最佳答案

std::replace 不会用其他序列替换序列。它用其他单个元素替换单个元素。除此之外,您将数字附加到字符串的方法不起作用。

尝试 boost::replace_firstboost::replace_all连同 boost::lexical_caststd::to_string (仅限 C++11)用于将数字转换为字符串。

using namespace boost;
std::string replace_str = std::string("smith") + lexical_cast<std::string>(number);
replace_first(tmpback[i], "smith", replace_str);

你也可以搜索子字符串,如果找到了,在它后面插入数字(转换为字符串):

std::string::size_type pos = tmpback[i].find("smith");
if (pos != std::string::npos)
{
// adding 5 because that's the length of "smith"
tmpback[i].insert(pos + 5, std::to_string(number));
}

关于c++ - 替换 vector 字符串中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9661339/

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