字符串中的子串修改、删除??求思想

li08240418 2011-11-04 08:47:44
Forexample:

有一字符串数组 和一个待匹配数组

char s[] = "jdfleifjlsfeurzboffddjmvcfaswdlopuejdaajfuerlsmaswdlipjwejrnf";
char c[] = "aswd";


1.如何找到s中的c并且删除它
2.如何统计s中的c的数量
3.怎样在s中找到c并且用其他字符或字符串替换
...全文
62 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
li08240418 2011-11-04
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 hongwenjun 的回复:]
C/C++ code
#include <iostream>
#include <string.h>
using namespace std;

char* replace_my(char* str, char c, const char* rc) ; // 查找替换
int find_cnt(char* str, char c); //查找计数
int main()
{
……
[/Quote]


非常感谢!!!
刀刀亮 2011-11-04
  • 打赏
  • 举报
回复
+1
[Quote=引用 2 楼 hongwenjun 的回复:]
C/C++ code

#include <iostream>
#include <string.h>
using namespace std;

char* replace_my(char* str, char c, const char* rc) ; // 查找替换
int find_cnt(char* str, char c); //查找计数
int main()
{
……
[/Quote]
hongwenjun 2011-11-04
  • 打赏
  • 举报
回复
#include <iostream>
#include <string.h>
using namespace std;

char* replace_my(char* str, char c, const char* rc) ; // 查找替换
int find_cnt(char* str, char c); //查找计数
int main()
{
char s[] = "jdfleifjlsfeurzboffddjmvcfaswdlopuejdaajfuerlsmaswdlipjwejrnf";
char c[] = " ->aswd<- ";
char str[1024]; // 保证 str足够大
strcpy(str, s);
cout << str << endl;
replace_my(str, 'c', ""); // 找到 'c' 删除
cout << str << endl << endl;



strcpy(str, s);
cout << str << endl;
cout << "找到'j'的次数" << find_cnt(str,'j') <<endl;
replace_my(str, 'c', c); // 找到 'c' 替换成 c
cout << str << endl << endl;

return 0;
}


char* replace_my(char* str, char c, const char* rc) // 调用函数前,保证str能展开空间
{
char* ret = str;
char* cp = str;
size_t cnt = 0;
int rcsize = (int)strlen(rc);

while (*cp) {
if (*cp == c)
cnt++; // 统计找到 c 的次数
++cp;
}

if (cnt <= 0) // 没找到 c
return ret;

cp = str;
int bufsize = strlen(str) + rcsize * cnt + 1;
char * buf = new char[bufsize]; // 建立缓冲区buf
char * ps = buf;

while (*cp) {
*ps = *cp;
if (*cp == c) { // 替换字符 c 为字符串 rc
memcpy(ps, rc, rcsize);
ps += (rcsize-1);
}
++cp; ++ps;
}
*ps = '\0'; // 封闭缓冲区buf
strcpy(str , buf);
delete[] buf;
return ret;
}


int find_cnt(char* str, char c) //查找计数
{
char* cp = str;
int cnt = 0;

while (*cp) {
if (*cp == c)
cnt++; // 统计找到 c 的次数
++cp;
}
return cnt;
}
hongwenjun 2011-11-04
  • 打赏
  • 举报
回复
http://topic.csdn.net/u/20111029/20/0bf449a0-9260-4ea8-9d57-9234a99befd5.html

1 和 3 都可以解决了
2. 这个就更加简单了,有个计数器就好了

69,382

社区成员

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

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