如何用标准c++库替换字符串的一部分?
QString s("hello $name"); // Example using Qt.
s.replace("$name", "Somename");
如何用标准c++库替换字符串的一部分?
QString s("hello $name"); // Example using Qt.
s.replace("$name", "Somename");
当前回答
您可以使用此代码删除减法,也可以替换,也可以删除额外的空白。 代码:
#include<bits/stdc++.h>
using namespace std;
void removeSpaces(string &str)
{
int n = str.length();
int i = 0, j = -1;
bool spaceFound = false;
while (++j <= n && str[j] == ' ');
while (j <= n)
{
if (str[j] != ' ')
{
if ((str[j] == '.' || str[j] == ',' ||
str[j] == '?') && i - 1 >= 0 &&
str[i - 1] == ' ')
str[i - 1] = str[j++];
else str[i++] = str[j++];
spaceFound = false;
}
else if (str[j++] == ' ')
{
if (!spaceFound)
{
str[i++] = ' ';
spaceFound = true;
}
}
}
if (i <= 1)
str.erase(str.begin() + i, str.end());
else str.erase(str.begin() + i - 1, str.end());
}
int main()
{
string s;
cin >> s;
for(int i = s.find("WUB"); i >= 0; i = s.find("WUB"))
s.replace(i,3," ");
removeSpaces(s);
cout << s << endl;
return 0;
}
其他回答
使用std:: string::替换:
s.replace(s.find("$name"), sizeof("$name") - 1, "Somename");
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;
}
如果所有字符串都是std::string,如果使用sizeof(),你会发现字符截断的奇怪问题,因为它是针对C字符串,而不是c++字符串。修复方法是使用std::string的.size()类方法。
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& 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()返回匹配的位置,所以我们不存在使迭代器失效的问题。
在c++ 11中,你可以像这样使用std::regex:
#include <regex>
...
std::string string("hello $name");
string = std::regex_replace(string, std::regex("\\$name"), "Somename");
对于转义字符,需要使用双反斜杠。