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

int main(void){
    char sen[100];
    char word[30];
    char rep[30];
    printf("Enter a sentence> ");
    gets(sen);
    printf("Enter a word to compare> ");
    gets(word);
    printf("Enter a word to replace with> ");
    gets(rep);
    int sen_len = strlen(sen);
    int word_len = strlen(word);
    char temp[30];
    char retSen[100];
    char rest[70];
    int i;
    int y=0;
    for(i=0; i<sen_len; i++){
        //Loop through characters in sentence until you reach a whitespace. ie, extract a word and put it in temp.
        if(sen[i] == ' '){
            //Compare the word with target word
            if(!strcmp(temp, word)){
                //In case of match, copy the part upto but not including the matching word and put it in the final string (retSen)
                strncpy(retSen, sen, sen_len-i);
            }else{
                //Clear temp and skip to next iteration
                y=0;
                temp[0] = '\0';
                continue;
            }
        }
        y++;
        //Repeatedly populate y with a word from sen
        temp[y] = sen[i];
    }
    int x=0;
    for(int j=i; j<sen_len; j++){
        //Populate another char array with the rest of the sentence after the matching word.
        rest[x] = sen[j];
    }
    //Join the part upto the matching word with the replacing word.
    strcat(retSen, rep);
    //Then join the rest of the sentence after the matching word to make the full string with the matching word replaced.
    strcat(retSen, rest);
    puts(retSen);
    return 0;
}

I'm trying to make a program that will take a sentence, a target word to replace and another word to replace the target with. This code isn't working. It just prints the replacing word + 'a' for some reason. How can I fix this code?

kerbx4
  • 9
  • 3
  • 2
    [Never use the `gets()` function](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-dangerous-why-should-it-not-be-used) — it is too dangerous, and is no longer a part of Standard C (and hasn't been for a decade). – Jonathan Leffler Apr 28 '21 at 19:02
  • It's doing the same thing with fgets(). The code doesn't work. – kerbx4 Apr 28 '21 at 19:04
  • 1
    My comment is a general guideline for C code presented on SO — do not use `gets()` in it because `gets()` cannot be used safely. If the code still doesn't work after replacing `gets()` with `fgets()`, you should learn how to use a debugger to find out what is going wrong and fix it. You should also show your sample inputs (the sentence you type, the word you're replacing, and the word you're replacing it with). Is the replacement text the same size as what's being replaced, or longer, or shorter? Usually, if the replacement text is longer than the source text, you have to allocate more space. – Jonathan Leffler Apr 28 '21 at 19:07
  • consider using `strstr()` – tstanisl Apr 28 '21 at 19:20
  • should it replace only the first occurrence of the word, or rather all occurrences? What to do if occurrences overlap (i.e. replacing `aba` in `ababa`)? – tstanisl Apr 28 '21 at 19:34
  • Just the first occurrence should do. Also I mean to replace a whole word in a sentence. aba isn't really a word in ababa. – kerbx4 Apr 28 '21 at 21:53

1 Answers1

0

In C, you need to build your own string substitution functions. I think that your use case could make good use of the strtok(), strcat() and strncat() functions,

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

// Prototypes:
int searchForWord( const char * haystack, const char * needle );
char * searchAndReplace( const char * haystack, const char * needle, const char * newNeedle );

/**
 * main
 */
int main()
{
    const char * sentence = "The quick brown fox jumped over the lazy dog." ;
    const char * wordToReplace = "fox" ;
    const char * replacementWord = "turtle" ; 

    // ... Search and replace...
    char * newSentence = searchAndReplace( sentence, wordToReplace, replacementWord ) ;
    
    // ... Show the result
    if ( newSentence ) {
        printf( "%s\n", newSentence ) ;
        free( newSentence ) ;
    } else {
        printf( "%s\n", sentence ) ;
    }

    return 0;
}

/**
 * Take a sentence, and replace the first occurrence of a word with another word.
 * 
 * Parameters:
 * haystack: the original sentence
 * needle: the word to search and replace
 * newNeed: the word to use as replacement
 * 
 * Returns:
 * A new modified string, or NULL if the word was never found.
 * 
 * Note: 
 * The result is dynamically allocated so it mut be freed once no longer needed.
 */
char * searchAndReplace( const char * haystack, const char * needle, const char * newNeedle ) 
{
    // ... Is the word in the sentence?
    int offset = searchForWord( haystack, needle ) ;
    if ( offset < 0 ) {
        fprintf( stderr, "searchAndReplace: %s not found in the given setence\n", needle );
        return NULL;
    }
    
    // ... From the found offset, determine the end offset of the word
    int offsetEnd = offset + strlen(needle);
    
    // ... Create a new buffer that will contain the modified sentence
    int newSize = strlen( haystack ) - strlen( needle ) + strlen( newNeedle ) + 1 ;
    char * result = (char*)malloc( newSize * sizeof(char) ) ;
    
    // ... Initialize the new buffer to a zero-length string
    result[ 0 ] = '\0';
    
    // ... Build the new sentence: first part (before the found word)
    if ( offset > 0 ) {
        strncat( result, haystack, offset) ;
    }
    
    // ... Build the new sentence: replaced word
    strcat( result, newNeedle ) ;
    
    // ... Build the new sentence: last part
    strncat( result, &haystack[ offsetEnd ], strlen(&haystack[ offsetEnd ]) ) ;
    
    return result ;
}

/**
 * Find the location of a word in a sentence, assuming words are whitespace-
 * delimited.
 * 
 * Returns: offset of the word in the sentence, or -1 if not found
 */
int searchForWord( const char * haystack, const char * needle ) 
{
    int result = -1 ;
    
    const char * delims = " \n\r\t" ; // whitespaces
    
    // ... Get a copy of haystack, as strtok() will alter it
    char * copy = strdup(haystack) ;
    
    // ... For each word in the sentence
    for ( char *p = strtok( copy, delims ); p != NULL; p = strtok( NULL, delims ) ) {
        // ... If the word matches what we're looking for
        if ( strcmp( p, needle ) == 0 ) {
            // ... Set the offset in the sentence
            result = p - &copy[ 0 ] ;

            // ... We're done searching
            break ;
        }
    }
    
    // .... Avoid memory leaks
    free( copy ) ;
    
    // ... Return whatever we found (or not)
    return result ;
}
El Stepherino
  • 600
  • 6
  • 18