Home > OS >  Trouble cycling through a string
Trouble cycling through a string

Time:10-20

I'm having trouble looping through a string and replacing instances of a character with a new character. I'm attempting to do so with a function that I've called replace.

// C program to replace all occurrences of a character with another in a string

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

/* Function declaration */
void replace(char *string, char toReplace, char replaceWith);
 
int main()
{
    char string[100]; 
    char toReplace, replaceWith;
 
    printf("Enter any string: ");
    scanf("%s", string);
    
    printf("Enter character to replace: ");
    scanf("%c\n", &toReplace);
    
    getchar();

    printf("Enter character to replace '%c' with: ", toReplace);
    scanf("%c\n", &replaceWith);
    
    replace(string, toReplace, replaceWith);

    // print new string
    printf("%s\n", string);
    
    return 0;
}
 
// Replaces the all occurrence of a character with another in given string.
void replace(char *string, char toReplace, char replaceWith)
{
    for (int i = 0; i <= strlen(string); i  )
    {
        if (string[i] == toReplace)  
        {
            string[i] = replaceWith;
        }
    }
}

Snippets of code causing me the most grief are:

printf("Enter character to replace '%c' with: ", toReplace);

Does not print what I expect it to.

if (string[i] == toReplace) 

Treats string[i] as the entire string, and not the individual members of the string.

CodePudding user response:

Changing scanf("%c\n", &toReplace); to scanf(" %c", &toReplace); helped, as this now ignores leading whitespace.

CodePudding user response:

Your replace function is OK except for a few details:

  • you should not recompute the length of the string at each iteration, especially as the compiler cannot assume the string to be constant since it gets modified inside the loop.
  • the test should be i < len where len is the length of the string. It seems incorrect to test the null terminator for replacement.
  • i should be defined with type size_t instead of int.

The problem you observe is linked to your usage of scanf():

  • "%c\n" will read the pending newline from stdin and then consume any subsequent white-space, which should not occur as the user typed the character they were prompted for. The next call will read this character, consume the newline and leave the second character typed pending in stdin.

  • note also that scanf("%s", string); will stop at the first white-space character and may cause a buffer overflow. Using fgets() seems a better approach for this.

Here is a modified version:

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

/* Function declaration */
void replace(char *string, char toReplace, char replaceWith);
 
int main() {
    char string[100]; 
    char toReplace, replaceWith;
 
    printf("Enter any string: ");
    if (!fgets(string, sizeof string, stdin))
        return 1;
    
    printf("Enter character to replace: ");
    if (scanf(" %c", &toReplace) != 1)
        return 1;
    
    printf("Enter character to replace '%c' with: ", toReplace);
    if (scanf(" %c", &replaceWith) != 1)
        return 1;
    
    replace(string, toReplace, replaceWith);

    // print new string
    printf("%s", string);
    
    return 0;
}
 
// Replaces the all occurrence of a character with another in given string.
void replace(char *string, char toReplace, char replaceWith) {
    for (size_t i = 0, len = strlen(string); i < len; i  ) {
        if (string[i] == toReplace) {
            string[i] = replaceWith;
        }
    }
}
  • Related