Problem 1 编写函数FindReplaceStr,其功能是从左到右地、不相交地、不递归地(参考示例)将字符串str中的所有子串find_str都替换成字符串replace_str(其长度与find_str的长度不一定相等),返回值为替换的次数,其原型为: int FindReplaceStr(char str[], const char find_str[], const char replace_str[]); 并在主函数中调用它处理输入。 输入、替换结果中的每个字符串的长度都不会超过99。 其实这就是各种文本编辑器中的“全部替换”功能。 请小心处理空白符。 字符串库函数可用列表: strlen() 注意:禁用STL。 input: 三个字符串,分别以换行符结束(换行符不计入字符串)。 output: 第一行:替换后的字符串; 第二行:替换次数。 input: ababa aba c output: cba 1 input: ababa aba ba output: baba 1
2条回答 默认 最新
- qfl_sdu 2021-05-16 17:47关注
代码如下,如有帮助,请采纳一下,谢谢。
#include <stdio.h> #include <string> using namespace std; int FindReplaceStr(char str[], const char find_str[], const char replace_str[]) { string s = str; int lenFind = strlen(find_str); //需要被替换的字符串的长度 int index = s.find(find_str); int tms = 0; while ( index >= 0 && index < s.length()-3) { tms++; string s1 = s.substr(0,index); string s2 = s.substr(index + lenFind,s.length() - index - lenFind ); s = s1 + replace_str + s2; index = s.find(find_str); } printf("替换后的字符串:%s\n",s.c_str()); printf("替换次数:%d\n",tms); return tms; } int main() { char buf[100] = {0}; char findstr[99] = {0}; char rpstr[99] = {0}; printf("请输入原始字符串:"); gets(buf); printf("请输入查找字符串:"); gets(findstr); printf("请输入替换字符串:"); gets(rpstr); int tms = FindReplaceStr(buf,findstr,rpstr); getchar(); getchar(); return 0; }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥15 安装svn网络有问题怎么办
- ¥15 Python爬取指定微博话题下的内容,保存为txt
- ¥15 vue2登录调用后端接口如何实现
- ¥65 永磁型步进电机PID算法
- ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
- ¥88 找成都本地经验丰富懂小程序开发的技术大咖
- ¥15 如何处理复杂数据表格的除法运算
- ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
- ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
- ¥15 latex怎么处理论文引理引用参考文献