首页 > 试题广场 >

使用C语言实现字符串中子字符串的替换。

[问答题]
使用C语言实现字符串中子字符串的替换
描述:编写一个字符串替换函数,如函数名为 strReplace(char* strSrc, char* strFind, char* strReplace),strSrc为原字符串,strFind是待替换的字符串,strReplace为替换字符串。
举个直观的例子吧,如:“ABCDEFGHIJKLMNOPQRSTUVWXYZ”这个字符串,把其中的“RST”替换为“ggg”这个字符串,结果就变成了: ABCDEFGHIJKLMNOPQgggUVWXYZ
推荐
void StrReplace(char *strSrc, char *strFind, char *strReplace);
#define M 100;
void main()
{
    char s[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    char s1[] = "RST";
    char s2[] = "ggg";
    StrReplace(s, s1, s2);
    printf("%s\n", s);
    return 0;
}
void StrReplace(char *strSrc, char *strFind, char *strReplace)
{
    int i = 0;
    int j;
    int n = strlen(strSrc);
    int k = strlen(strFind);
    for (i = 0; i
{
    if (*(strSrc + i) == *strFind)
        {
            for (j = 0; j
        {
            if (*(strSrc + i + j) == *(strFind + j))
                {
                    *(strSrc + i + j) = *(strReplace + j);
                }
                else continue;
            }
        }
    }
}
发表于 2014-10-25 00:26:19 回复(0)
#include <stdio.h>
void strReplace(char* strSrc, char* strFind, char* strReplace)
{  if(strSrc==NULL  ||strFind==NULL||strReplace==NULL) 
    return;
char newstring[512];     char *findpos = NULL;     findpos = strstr(strSrc,strFind);     int str_lenth = 0; if(findpos!=NULL)   {     do     {   memset(newstring,0 ,sizeof(newstring));     str_lenth = findpos - strSrc;   memcpy(newstring,strSrc,str_lenth); strcat(newstring,strReplace,strlen(strReplace));   strcat(newstring,strlen(strFind)+findpos); strcpy(strSrc,newstring); findpos = strstr(strSrc,strFind); }while(findpos);   }
return strSrc;
}
int main(void)
{
char strSrc[]="RSTDEFGRSTKLMNOPQRSTUVWRS";
char
  strFind[]="RST";
char
  strReplace[]="ggg";
strReplace(   strSrc,  
   strFind,   strReplace   );
 puts(strSrc);
}
编辑于 2016-08-05 23:36:31 回复(0)
#include<iostream>
using namespace std;
void strReplace1(char* strSrc,    char* strFind,    char* strReplace)
{
    if(strSrc==NULL  ||strFind==NULL||strReplace==NULL)
    return;

    char *replace=strReplace;
    char *find = strFind;
    while(*strSrc!='\0')
    {
        if(*strSrc==*strFind)
        {
            char *begin = strSrc;
            while(*strSrc!='\0' &&*strFind!='\0' && (*strSrc++==*strFind++));
            if(*strFind=='\0')
            {
                while(*strReplace!='\0' && (*begin++=*strReplace++));
                strReplace=replace;
            }
            strFind=find;
    }
    else
        strSrc++;
    }
}

int main()
{
    char strSrc[]="RSTDEFGRSTKLMNOPQRSTUVWRS";
    char strFind[]="RST";
    char strReplace[]="ggg";
    strReplace1(   strSrc,    strFind,   strReplace   );
    cout<<strSrc;
}

编辑于 2015-07-18 16:52:34 回复(0)