поиск подстроки в строке - PullRequest
       2

поиск подстроки в строке

0 голосов
/ 14 декабря 2018

Напишите программу, которая находит все экземпляры указанного шаблона в данной строке и заменяет их другой строкой.Базовая строка, шаблон поиска и строка замены будут предоставлены пользователем.Я написал такую ​​программу, но что-то не так с ней, и я не мог понять, что.

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 голосов
/ 14 декабря 2018

Надеюсь, что следующая функция поможет вам заменить первое вхождение

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++;
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...