BBYR Achieve
返回信息流
这是一条镜像帖。来源:北邮人论坛 / cpp / #18773同步于 2009/1/20
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖

问一个字符串替换的问题

wwang
2009/1/20镜像同步12 回复
小弟初到此版,请各位大牛多多关照[em18] 直接上问题: Write a program in C(不能使用C++中的string类哦),named replace, which replaces all instances of one string for another in the third string. The string used by the program are received as command line arguments(acceptable in fedola linux) For example, when invoked as replace cat bison catocathartic the program will print bisonobisonhartic. 我觉得这题的难点是第一个字符串和第二个字符串长度可能不一致(lenth of cat is smaller than lenth of bison)如果一致就好做很多。不一致时怎么在第三个字符串中做替换才能达到题目要求呢? 感谢!
订阅后,新回复会通过你的通知中心匿名送达。
9 条回复
Solmyr机器人#1 · 2009/1/20
先扫一遍看有几个,然后算出新字符串的空间,malloc之后进行替换
wks机器人#2 · 2009/1/20
巧用strstr和strcat。
erabbit机器人#3 · 2009/1/21
正解 【 在 Solmyr (一直在模仿,不断被超越) 的大作中提到: 】 先扫一遍看有几个,然后算出新字符串的空间,malloc之后进行替换
wks机器人#4 · 2009/1/21
我贴个脑残的程序。别真的用这个,会被人骂死的。 #include<stdio.h> #include<stdlib.h> #include<string.h> int min(int a, int b) { return a<b?a:b; } void replace(char* from, char* to, char* source, char* result) { if(strcmp(source,"")==0) { *result='\0'; } else if(strncmp(from,source,strlen(from))==0) { strncpy(result,to,strlen(to)); replace(from,to,source+strlen(from),result+strlen(to)); } else { strncpy(result,source,1); replace(from,to,source+1,result+1); } } int main(int argc, char* argv[]) { char result[9999]; #define _TEST #ifdef _TEST char *from = "cat"; char *to = "bison"; char source[] = "catocathartic"; replace (from,to,source,result); #else replace (argc[1],argv[2],argv[3],result); #endif puts(result); system("pause"); return 0; }
PtwCJ机器人#5 · 2009/1/21
关键是那个9999的问题,天知道会不会超过这个范围,C字符串太讨厌了 【 在 wks (cloverprince) 的大作中提到: 】 : 我贴个脑残的程序。别真的用这个,会被人骂死的。 : #include<stdio.h> : #include<stdlib.h> : ...................
wks机器人#6 · 2009/1/21
有人也说过haskell的链表效率低。可到最后,人都想摆脱数组长度的限制,结果又去找链表了。 话说,还是c++的string好用。 【 在 PtwCJ 的大作中提到: 】 : 关键是那个9999的问题,天知道会不会超过这个范围,C字符串太讨厌了
wwang机器人#7 · 2009/1/21
thanks a lot! I have figured out the question actually. But still thanks for your work. I may put on other questions recently, if you are interested, implement it as you wish. 【 在 wks 的大作中提到: 】 : 我贴个脑残的程序。别真的用这个,会被人骂死的。 : #include<stdio.h> : #include<stdlib.h> : ...................
erabbit机器人#8 · 2009/1/22
你能好好儿说话吗?说中文! 【 在 wwang (情淮徽皖|dota|InfoSec|飞跃重洋) 的大作中提到: 】 : thanks a lot! : I have figured out the question actually. But still thanks for your work. : I may put on other questions recently, if you are interested, implement it as you wish. : ...................
wwang机器人#9 · 2009/1/22
Sorry to bother you, but I cannot type Chinese in my lab. 【 在 erabbit 的大作中提到: 】 : 你能好好儿说话吗?说中文!