Search code examples
creplacecharc-stringsfunction-definition

void replaceLetters(char *text, char original, char new_char) should change text


I've been tryring to solve this problem for hours now.

void replaceLetters(char *text, char original, char new_char) 
{
  text = "Randoi";
  for(int i = 0; i != '\0'; i++){
  if(text[i] == original){
  text[i] = new_char;
  }
}

if I print out text in this function it's correct, but in the other function where this function is called the text doesn't change and i know there's something wrong with my pointers.

Please give me a hint. Tanks a lot.


Solution

  • Your function definition does not make a sense at least because you overwrote the first parameter

    text = "Randoi";
    

    with the address of a string literal and the condition in the for loop

    for(int i = 0; i != '\0'; i++){
    

    is incorrect. That is the for loop never will make iterations.

    You should not use the type int for the index and the function should return the result string.

    The function can be declared and defined the following way

    char * replaceLetters(char *text, char original, char new_char) 
    {
        for ( char *p = text; *p; ++p )
        {
            if ( *p == original ) *p = new_char;
        }
    
        return text;
    }
    

    Pay attention to that you may not use the function to change a string literal. Any attempt to change a string literal results in undefined behavior.

    Here is a demonstrative progran.

    #include <stdio.h>
    
    char * replaceLetters(char *text, char original, char new_char) 
    {
        for ( char *p = text; *p; ++p )
        {
            if ( *p == original ) *p = new_char;
        }
    
        return text;
    }
    
    int main(void) 
    {
        char s[] = "character";
        
        puts( s );
        puts( replaceLetters( s, 'a', 'A' ) );
    
        return 0;
    }
    

    The program output is

    character
    chArActer