在字符串中搜索子字符串

时间:2018-12-14 06:28:29

标签: c string

编写一个程序,在给定的字符串中查找指定模式的所有实例并替换 他们与另一个字符串。基本字符串,搜索模式和替换字符串将为 由用户提供。我写了这样的程序,但是它出了点问题,我听不懂。

input:
 enter the sentence: hello world
 enter the word which u want to replace: world
enter the new word: hello

output:
The word appears one times
#define SIZE 80

void newsentence(char a[], char b[], char c[], int n, int k);
void array(int f, int s, int g, char buff[], char b[], char c[], int n, int k);

int main()
{
    char a[SIZE], b[SIZE], c[SIZE];
    int k;

    printf("Enter the sentence: ");
    gets(a);
    printf("\nEnter the word which u want to replace: ");
    scanf("%s",b);
    printf("\nEnter the new word: ");
    scanf("%s",c);

    int n =0;
    char *temp;
    temp =a;

    while((temp =strstr(temp,b))!= NULL){
        n++;
        temp++;
        k = strstr(temp,b)-b;
    }
    printf("The word appears %d times",n);

    newsentence(a,b,c,n,k);
}

void newsentence(char a[], char b[], char c[], int n, int k)
{
    int f, s, g;
    char buff;

    f=strlen(a);
    s=strlen(b);
    g=strlen(c);

    strcpy(buff,a);

    array(f,s,g, buff,b,c,n,k);
}
void array(int f, int s, int g, char buff[], char b[], char c[], int n, int k)
{
    int i,j;
    int q;
    q = k +s - 1;

    for(j = 0; k<=q ;k++, j++)
    {
        if(strcmp(buff[k],b[j])==0){
            strcmp(buff[k],c[i]);
        }
    }

    for(i = 0; i<SIZE;i++){
        printf("Yout new string is: %c",buff[i]);
    }
}

1 个答案:

答案 0 :(得分:0)

希望以下功能可以帮助您替换首次出现的情况

void str_find_replace(char *str, char *find, char *replace)
{
    size_t find_len,replace_len;
    char *str_end;

    find_len = strlen(find);
    replace_len = strlen(replace);
    str_end = strlen(str);

    while(*str){
        if(!strncmp(str,find,find_len) {
            memmove(str+replace_len,str+find_len, str_end - (str + find_len) + 1);
            memcpy(str,replace,replace_len);
            return;
        }
        str++;
    }
}

如果要替换所有出现的内容,请使用以下功能

void str_find_replace(char *str, char *find, char *replace)
{
    size_t find_len,replace_len;
    char *str_end;

    find_len = strlen(find);
    replace_len = strlen(replace);
    str_end = strlen(str);

    while(*str){
        if(!strncmp(str,find,find_len) {
            memmove(str+replace_len,str+find_len, str_end - (str + find_len) + 1);
            memcpy(str,replace,replace_len);
            str += replace_len;
            str_end = str + strlen(str);
            continue;
        }
        str++;
    }
}