把字符串str1中的所有子串str2替换为str3:。求c语言高手编程
1个回答
展开全部
下面是一个replace字符串的例子:
#include<stdio.h>
#include<string.h>
#define MAXLENGTH 100
//调用的时候必须确保s1的长度足够容纳替换的字符串。
void replace(char *s1, char *s2, char *s3)
{
int len1 = strlen(s1), len2=strlen(s2), len3 = strlen(s3);
char buf[MAXLENGTH]; //保存替换后的字符串
int i, j, k, l;
for(i=0, k=0; i<len1-len2;) {
for(j=0; j<len2; j++) {
if(s1[i+j] != s2[j]) break;
}
if(j == len2) {
l = 0;
while(l<len3) buf[k++] = s3[l++];
i += len2;
continue;
} else {
buf[k++] = s1[i++];
}
}
while(i<len1) buf[k++] = s1[i++];
buf[k] = '\0';
strcpy(s1, buf); //将替换后的串复制给s1.
}
int main()
{
char str1[MAXLENGTH] = "abc123efkdloicleas123lekcle";
char str2[] = "123";
char str3[] = "###";
replace(str1, str2, str3);
printf("替换后: %s\n", str1);
char c;
scanf("%c",&c);
return 0;
}
#include<stdio.h>
#include<string.h>
#define MAXLENGTH 100
//调用的时候必须确保s1的长度足够容纳替换的字符串。
void replace(char *s1, char *s2, char *s3)
{
int len1 = strlen(s1), len2=strlen(s2), len3 = strlen(s3);
char buf[MAXLENGTH]; //保存替换后的字符串
int i, j, k, l;
for(i=0, k=0; i<len1-len2;) {
for(j=0; j<len2; j++) {
if(s1[i+j] != s2[j]) break;
}
if(j == len2) {
l = 0;
while(l<len3) buf[k++] = s3[l++];
i += len2;
continue;
} else {
buf[k++] = s1[i++];
}
}
while(i<len1) buf[k++] = s1[i++];
buf[k] = '\0';
strcpy(s1, buf); //将替换后的串复制给s1.
}
int main()
{
char str1[MAXLENGTH] = "abc123efkdloicleas123lekcle";
char str2[] = "123";
char str3[] = "###";
replace(str1, str2, str3);
printf("替换后: %s\n", str1);
char c;
scanf("%c",&c);
return 0;
}
追问
谢谢了,不过是大一新生,看不太懂!!
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询