C++字符串的查找与替换

djglpy521 2012-06-20 10:05:17
要求手动输入一段正文
输入要替换的字符串
出入替换的字符串
替换要循环
...全文
446 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
hongwenjun 2012-06-20
  • 打赏
  • 举报
回复
#include <iostream>
#include <string>

int main()
{
using namespace std;
string str = "Hello world! Hello world! Hello world! Hello world! ";
string s1 = "Hello";
string s2 = "你好世界!";

size_t pos = str.find(s1);
while (pos != string::npos) {
str.replace(pos, s1.length(), s2);
pos = str.find(s1);
}

cout << str << endl;
return 0;
}
zjs100901 2012-06-20
  • 打赏
  • 举报
回复
替换要循环是不是指下面情况?
源字符串aabcc,将abc替换为b,则aabcc -> abc -> b
还是仅仅就像记事本里的全部替换而己?
rendao0563 2012-06-20
  • 打赏
  • 举报
回复

这段代码可用. 不过效率比较低. 对效率有要求请用C方式.

static inline std::string ReplaceString(std::string strSrc,std::string strPos,std::string strStr)
{
std::basic_string<char>::iterator IterL;
std::basic_string <char>::size_type indexCh1a = 0;
std::basic_string <char>::size_type off = 0;
std::string result6a = strSrc;
if (strPos.empty())
{
return strSrc;
}
while((indexCh1a = strSrc.find(strPos,off)) != std::string::npos)
{
IterL = strSrc.begin( ) + indexCh1a;
off = indexCh1a + strStr.size();
result6a = strSrc.replace( IterL , IterL+strPos.size() , strStr );
}
return result6a;
}
modicum_lf 2012-06-20
  • 打赏
  • 举报
回复


void f(char *Src, char *DisPlace)
{
int len = strlen(DisPlace) + 1;
char * tmp = (char*)malloc(len);
memset(tmp, 0, strlen(DisPlace) + 1 );

for (int i = 0; i < ( strlen(Src) + 1); ++ i)
{
memcpy(tmp, Src, len);
if( 0 == strcmp(tmp, DisPlace ) )
{
memcpy(Src, tmp, len);
i += len;
}
}


}

djglpy521 2012-06-20
  • 打赏
  • 举报
回复
就像将abc you abc you abc you abc youf中的abc全部替换成you
变成you you you you you you you you一样 但要求原字符串与查找字符串要输入,替代字符串也要用手动输入
并完成替换 急求 请各位大神帮忙

69,368

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧