搜索

C语言显示替换后的字符串

发布网友 发布时间:2022-04-22 18:03

我来回答

2个回答

热心网友 时间:2023-06-26 03:53

二楼好像没理解题意,有时间我写一个,但分数也太少了吧?悲哀!

/*
以下程序可以实现替换字符串中的字符串
*/

#include <stdio.h>
#include <string.h>

char * replace(char *str, char *str1, char *str2, char *strretu)
{
char *str_temp = str;
char *str1_temp = str1;
char *str2_temp = str2;
char *strretu_temp = NULL;

unsigned long char_size = (unsigned long)sizeof(char);
/*计算字符长度*/
unsigned long i,j,rep_acc = 0;
unsigned long str_len = strlen(str);
unsigned long str1_len = strlen(str1);
unsigned long str2_len = strlen(str2);

/*首先找出Str里有几个地方要被替换的*/
for(; str_temp - str < str_len; )
{
for(i = 0; i < str1_len; i++)
{
if(*str_temp++ != *str1_temp++)
{
str1_temp = str1;
break;
}
else
{
if(i == str1_len - 1)
{
str1_temp = str1;
rep_acc++;
}
}
}
}
str1_temp = str1;
str_temp = str;

/*分配所需内存*/
strretu = strretu_temp = malloc(((str_len - str1_len * rep_acc) + str2_len * rep_acc + 1) * char_size);
/*替换*/
for(; str_temp - str < str_len; )
{

for(i = 0; i < str1_len; i++)
{
*strretu_temp++ = *str_temp;

if(*str_temp++ != *str1_temp++)
{
str1_temp = str1;
break;
}
else
{

if(i == str1_len - 1)
{
strretu_temp = strretu_temp - str1_len;

for(i = 0; i < str2_len; i++)
{
*strretu_temp++ = *str2_temp++;
}
str2_temp = str2;
str1_temp = str1;
}
}
}
}
*strretu_temp = '\0';
str1_temp = str1;
str_temp = str;
str2_temp = str2;

return(strretu);
}

int main(void)
{
/*
char *str = "asdf123asdf123aa";
char *str1 = "123";
char *str2 = "999";

char *str = "eeeeee1245eeeeeeeeee1245eeeeeeeeeeeee1245eeeeeeeeeeee1245eeeeeeeeeeeee";
char *str1 = "1245";
char *str2 = "ffffffff";

*/
char *str = "fffffff0fffffff1fffffff2fffffff3fffffff4fffffff5fffffff6fffffff7fffffff8fffffff9";
char *str1 = "fffffff";
char *str2 = "月梦";

char *strretu = NULL;

printf("str = %s\n", str);
printf("str1 = %s\n", str1);
printf("str2 = %s\n", str2);

strretu = replace(str, str1, str2, strretu);

printf("strretu = %s\n", strretu);

getch();

free(strretu);
return 0;
}

热心网友 时间:2023-06-26 03:53

#include <stdio.h>
replace(char *str, char *str1, char *str2, char *strretu){
int i,j=0;
int temp=0;
char* p;
for(i=0;str[i]!='\0';i++){
if(str[i]==str1[0]){
for(temp=0;str1[temp]!='\0';temp++){
if(str1[temp]!=str[i+temp])break;
}
if(str1[temp]=='\0'){
i+=temp-1;
strcat(strretu,str2);
j+=strlen(str2);
}
}else{
strretu[j]=str[i];
j++;
}
}
strretu[i]='\0';
}

int main(int argc, char *argv[])
{

char *str="asdf123asdf123aa";
char *str1="123";
char *str2="999";
char *strretu;
replace(str, str1, str2,strretu);
printf("%s\n",strretu);
return 0;
}
声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。
E-MAIL:11247931@qq.com
Top