Home > Mobile >  Replace a word in string
Replace a word in string

Time:07-19

How do i make below program work properly, The main problem i have seen so far is str1 is not defined properly which may be the real cause for the program not working properly.

#include<stdio.h>
#include<string.h>
int main()
{
    char string[]="We will rock you";
    char s1[10],s2[10];
    printf("Enter string 1 ");
    gets(s1);
    printf("Enter string 2 ");
    gets(s2);
    int start,end,compare;
    for(int i=0;string[i]!='\0';i  )
     if(string[i]==s1[0])
     {
        start=i;
        break;
     }
    //printf("%d",start);
    end=start strlen(s1);
    //printf("\n%d",end);
    char str1[30],check[10];

//Defining string 1
    for(int i=0;i<start;i  )
     str1[i]=string[i];
    //printf("\n%sd",str1);
    
//Defining check
    for(int i=start;i<end;i  )
     check[i-start]=string[i];
     
    //printf("\n%s\n",check,str1);
    compare=strcmp(check,s1);
    //printf("\n%d",compare);
    
    if(compare==0)
     strcat(str1,s1);
     printf("\n%s",str1);
     
    for(int i=end,j=strlen(str1);i<strlen(string);i  )
    {
        str1[j]=string[i];
    }
    strcpy(string,str1);
    
    printf("\n%s",string);
}

I know this is not the best way to do it, it has so many loopholes as it wont work for words appearing again and it may also change words like (ask, task or asking) if str1 is given ask. But still help me , What am i doing wrong???

CodePudding user response:

Function replacing string in the string.

char *strreplace(char *haystack, const char *needle, const char *replace, char *buff)
{
    int length = strlen(haystack);
    int needlelength = strlen(needle);
    int replacelength = strlen(replace);
    char *ptr = buff;
    char *start, *source, *dest;

    if (buff == NULL)
    {
        ptr = malloc((length   1) * sizeof(char));
        source = ptr;
        dest = haystack;
    }
    else
    {
        source = haystack;
        dest = buff;
    }

    if (ptr != NULL)
    {
        if (buff == NULL) strcpy(ptr, haystack);
        else
        {
           if (!length) 
            {
                *buff = 0;
            }
        }
        while (needlelength && *source)
        {
            size_t chunklen;
            char *result;

            start = source;
            if ((result = strstr(source, needle)) == NULL)
            {
                strcpy(dest, source);
                break;
            }
            chunklen = result - start;
            strncpy(dest, start, chunklen);
            dest  = chunklen;
            strcpy(dest, replace);
            dest  = replacelength;
            source = result;
            source  = needlelength;
        }
        if (buff == NULL)
        {
            free(ptr);
            ptr = haystack;
        }
        else
        {
            ptr = buff;
        }
    }
    return ptr;
}

CodePudding user response:

What am i doing wrong???

For starters the function gets is unsafe and is not supported by the C Standard. Instead either use scanf or fgets.

If in this for loop

int start,end,compare;
for(int i=0;string[i]!='\0';i  )
 if(string[i]==s1[0])
 {
    start=i;
    break;
 }

the condition string[i]==s1[0] does not evaluate to true then the variable start will have an indeterminate value because it is not initialized and all the subsequent code after the for loop invokes undefined behavior because there is used the uninitialized variable start.

If the condition evaluates to true then the value of end

end=start strlen(s1);

can be larger than the length of the original string string. That again can invoke undefined behavior in this for loop

for(int i=0;i<start;i  )
 str1[i]=string[i];

After this for loop

for(int i=start;i<end;i  )
 check[i-start]=string[i];
 
//printf("\n%s\n",check,str1);
compare=strcmp(check,s1);

the array check does not contain a string. So calling the function strcmp also invokes undefined behavior.

It seems that in this call there is at least a typo.

if(compare==0)
 strcat(str1,s1)

it seems you mean

strcat( str1, s2 );
              ^^^ 

If s1 was not found in string then this loop

for(int i=end,j=strlen(str1);i<strlen(string);i  )
{
    str1[j]=string[i];
}

just does not make a sense.

Pay attention to that in general the length of s2 can be greater than the length of s1. In this case you may not change s1 to s2 within string declared like

char string[]="We will rock you";

because that results in accessing memory outside the array.

CodePudding user response:

Hello and Sorry for bad English. I think this code can help you

char* replace ( char text[] , char mainchar, char replace_char )
{
    char    out [120];
    char*   out_pointer  = out  ;
    register char      index_2=0;
    for ( register char index_1 = 0 ; index_1 < strlen (text) ;   index_1 )
    {
        if ( text[index_1] != mainchar )
        {
            out_pointer[index_2]=text[index_1];
              index_2 ;
        }
        else
        {
            out_pointer[index_2]=replace_char;
              index_2 ;
        }
    }
    return out_pointer;
}

To use this function in your source code, proceed as follows :

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

int main ()
{
    char* replace ( char text[] , char mainchar, char replace_char )
    {
        char    out [120];
        char*   out_pointer  = out  ;
        register char      index_2=0;
        for ( register char index_1 = 0 ; index_1 < strlen (text) ;   index_1 )
        {
            if ( text[index_1] != mainchar )
            {
                out_pointer[index_2]=text[index_1];
                  index_2 ;
            }
            else
            {
                out_pointer[index_2]=replace_char;
                  index_2 ;
            }
        }
        return out_pointer;
    }
    char Array[100];
    strcpy (Array, replace("Hello", 'H', 'e'));
    printf ("%s", Array);
}
  • Related