在C ++中是否可以用另一个字符串替换字符串的一部分?
基本上,我想这样做:
QString string("hello $name");
string.replace("$name", "Somename");
但我想使用标准C ++库。
有一个函数可以在字符串中找到一个子字符串(find
),还有一个用另一个字符串(replace
)替换字符串中特定范围的函数,所以你可以将它们组合起来得到你想要的效果:
bool replace(std::string& str, const std::string& from, const std::string& to) {
size_t start_pos = str.find(from);
if(start_pos == std::string::npos)
return false;
str.replace(start_pos, from.length(), to);
return true;
}
std::string string("hello $name");
replace(string, "$name", "Somename");
在回应评论时,我认为replaceAll
可能看起来像这样:
void replaceAll(std::string& str, const std::string& from, const std::string& to) {
if(from.empty())
return;
size_t start_pos = 0;
while((start_pos = str.find(from, start_pos)) != std::string::npos) {
str.replace(start_pos, from.length(), to);
start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'
}
}
wstring myString = L"Hello $$ this is an example. By $$.";
wstring search = L"$$";
wstring replace = L"Tom";
for (int i = myString.find(search); i >= 0; i = myString.find(search))
myString.replace(i, search.size(), replace);
如果您想快速完成,可以使用双扫描方法。伪代码:
我不确定这是否可以针对就地算法进行优化。
和一个C ++ 11代码示例,但我只搜索一个字符。
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
void ReplaceString(string& subject, char search, const string& replace)
{
size_t initSize = subject.size();
int count = 0;
for (auto c : subject) {
if (c == search) ++count;
}
size_t idx = subject.size()-1 + count * replace.size()-1;
subject.resize(idx + 1, '\0');
string reverseReplace{ replace };
reverse(reverseReplace.begin(), reverseReplace.end());
char *end_ptr = &subject[initSize - 1];
while (end_ptr >= &subject[0])
{
if (*end_ptr == search) {
for (auto c : reverseReplace) {
subject[idx - 1] = c;
--idx;
}
}
else {
subject[idx - 1] = *end_ptr;
--idx;
}
--end_ptr;
}
}
int main()
{
string s{ "Mr John Smith" };
ReplaceString(s, ' ', "%20");
cout << s << "\n";
}
我刚刚学习C ++,但是编辑之前发布的一些代码,我可能会使用这样的东西。这使您可以灵活地替换1个或多个实例,还可以指定起点。
using namespace std;
// returns number of replacements made in string
long strReplace(string& str, const string& from, const string& to, size_t start = 0, long count = -1) {
if (from.empty()) return 0;
size_t startpos = str.find(from, start);
long replaceCount = 0;
while (startpos != string::npos){
str.replace(startpos, from.length(), to);
startpos += to.length();
replaceCount++;
if (count > 0 && replaceCount >= count) break;
startpos = str.find(from, startpos);
}
return replaceCount;
}
我自己的实现,考虑到字符串只需要调整一次,然后替换可能会发生。
template <typename T>
std::basic_string<T> replaceAll(const std::basic_string<T>& s, const T* from, const T* to)
{
auto length = std::char_traits<T>::length;
size_t toLen = length(to), fromLen = length(from), delta = toLen - fromLen;
bool pass = false;
std::string ns = s;
size_t newLen = ns.length();
for (bool estimate : { true, false })
{
size_t pos = 0;
for (; (pos = ns.find(from, pos)) != std::string::npos; pos++)
{
if (estimate)
{
newLen += delta;
pos += fromLen;
}
else
{
ns.replace(pos, fromLen, to);
pos += delta;
}
}
if (estimate)
ns.resize(newLen);
}
return ns;
}
用法可以是这样的:
std::string dirSuite = replaceAll(replaceAll(relPath.parent_path().u8string(), "\\", "/"), ":", "");
使用C ++ 11,您可以像这样使用std::regex
:
std::string string("hello $name");
string = std::regex_replace(string, std::regex("\\$name"), "Somename");
转义转义字符需要双反斜杠。
std::string
有一个replace
方法,这是你在寻找什么?
你可以尝试:
s.replace(s.find("$name"), sizeof("$name") - 1, "Somename");
我没有尝试过自己,只需阅读有关find()
和replace()
的文档。
要返回新字符串,请使用以下命令:
std::string ReplaceString(std::string subject, const std::string& search,
const std::string& replace) {
size_t pos = 0;
while ((pos = subject.find(search, pos)) != std::string::npos) {
subject.replace(pos, search.length(), replace);
pos += replace.length();
}
return subject;
}
如果您需要性能,这里是一个修改输入字符串的优化函数,它不会创建字符串的副本:
void ReplaceStringInPlace(std::string& subject, const std::string& search,
const std::string& replace) {
size_t pos = 0;
while ((pos = subject.find(search, pos)) != std::string::npos) {
subject.replace(pos, search.length(), replace);
pos += replace.length();
}
}
测试:
std::string input = "abc abc def";
std::cout << "Input string: " << input << std::endl;
std::cout << "ReplaceString() return value: "
<< ReplaceString(input, "bc", "!!") << std::endl;
std::cout << "ReplaceString() input string not modified: "
<< input << std::endl;
ReplaceStringInPlace(input, "bc", "??");
std::cout << "ReplaceStringInPlace() input string modified: "
<< input << std::endl;
输出:
Input string: abc abc def
ReplaceString() return value: a!! a!! def
ReplaceString() input string not modified: abc abc def
ReplaceStringInPlace() input string modified: a?? a?? def
是的,你可以这样做,但是你必须找到带有字符串的find()成员的第一个字符串的位置,然后用它的replace()成员替换它。
string s("hello $name");
size_type pos = s.find( "$name" );
if ( pos != string::npos ) {
s.replace( pos, 5, "somename" ); // 5 = length( $name )
}
如果你打算使用标准库,你应该真正掌握一本书The C++ Standard Library的副本,它很好地涵盖了所有这些内容。
这听起来像一个选项
string.replace(string.find("%s"), string("%s").size(), "Something");
你可以将它包装在一个函数中,但这个单行解决方案听起来是可以接受的问题是这只会改变第一次出现,你可能想要循环它,但它也允许你用相同的标记将几个变量插入到这个字符串中(%s
)
我一般用这个:
std::string& replace(std::string& s, const std::string& from, const std::string& to)
{
if(!from.empty())
for(size_t pos = 0; (pos = s.find(from, pos)) != std::string::npos; pos += to.size())
s.replace(pos, from.size(), to);
return s;
}
它反复调用std::string::find()
来定位搜索到的字符串的其他出现,直到std::string::find()
找不到任何东西。因为std::string::find()
返回匹配的位置,所以我们没有使迭代器无效的问题。
如果所有字符串都是std :: string,那么如果使用sizeof()
,你会发现字符截断的奇怪问题,因为它意味着C字符串,而不是C ++字符串。修复是使用.size()
的std::string
类方法。
sHaystack.replace(sHaystack.find(sNeedle), sNeedle.size(), sReplace);
这取代了内联的sHaystack - 不需要在那里做一个=赋值。
用法示例:
std::string sHaystack = "This is %XXX% test.";
std::string sNeedle = "%XXX%";
std::string sReplace = "my special";
sHaystack.replace(sHaystack.find(sNeedle),sNeedle.size(),sReplace);
std::cout << sHaystack << std::endl;
std::string replace(std::string base, const std::string from, const std::string to) {
std::string SecureCopy = base;
for (size_t start_pos = SecureCopy.find(from); start_pos != std::string::npos; start_pos = SecureCopy.find(from,start_pos))
{
SecureCopy.replace(start_pos, from.length(), to);
}
return SecureCopy;
}