![](/img/trans.png)
[英]Replacing instances of a given std::string with another std::string in C++
[英]C++ :- Replacing a piece of string by another string
我正在尝试编写一个REPLACE
函数,它将用required
字符串替换given
的字符串。 当我在纸上干燥运行该功能时,一切似乎都很好,但在执行时,它没有给出正确的输出。 代码如下: -
string REPLACE(string src,string reqd,string given)
{
int i,j,k;
int pos = FIND(src,given);
if(pos==-1)
return "";
else
{
char *arr = new char[src.length()+reqd.length()-given.length()]; // creating the array that will hold the modified string
for(i=0;i<pos;i++)
arr[i] = src[i]; // copying the initial part of the string
for(i=pos,j=0;i<pos+reqd.length()+1&&j<reqd.length();i++,j++)
arr[i] = reqd[j]; // copying the required string into array
for(i=pos+reqd.length()+1,k=0;i<sizeof(arr);i++,k++)
arr[i] = src[pos+given.length()+k]; // copying the remaining part of source string into the array
return arr;
}
}
这里的FIND
也是由我编写的,并且在许多情况下已经过测试。 我在FIND
没有看到任何错误。
我不认为将std :: string与char数组混合是个好主意。 以下应该工作:
string REPLACE(string src,string reqd,string given)
{
int pos = FIND(src,given);
src.replace( pos, given.size(), reqd );
return src;
}
for(i=pos+reqd.length()+1,k=0; i<sizeof(arr); i++,k++)
// ^^^^^^^^^^^
// This is always the same
sizeof(arr)
与sizeof(char*)
,是编译时常量值。 您需要自己保持动态分配的数组的大小(或者,更好的是,只需使用std::string
)。
假设您不想重新发明轮子:
string REPLACE(string src,string reqd,string given)
{
string str(src);
size_t pos = str.find(given);
if(pos == std::string::npos)
return "";
str.replace(pos, given.length(), reqd);
return str;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.