How to replace specific characters in a string with other characters

前端 未结 3 1037
无人及你
无人及你 2021-01-14 04:16

I am trying to make a program that will take as input a string and replace all the vowels with the * symbol. So, for \"hello world\", star_vowels should return \"h*ll* w*rld

3条回答
  •  我在风中等你
    2021-01-14 04:46

    By incrementing the j at the beginning you will lose the 0 index (the first character).

    Since you want to return new data to the outside world (outside the function scope), you either allocate memory for the new data outside the function, and pass in a pointer of that data to this function, or you just allocate dynamic memory inside this function - remember to delete it.

    One implementation would be:

    char *star_vowels(char s[]){
        // let's allocate memory for the new string.
        // its size should be strlen(s) + 1 (the ending char).
        char *final = malloc(strlen(s) + 1); 
    
        int j = 0;
        while (s[j] != 0){
            if (s[j] == 'a' || s[j] == 'e' || s[j] == 'i' || s[j] == 'o' || s[j] == 'u'){
                final[j] = '*';
            } else {
                final[j] = s[j];
            }
            j++;
        }
        final[j] = 0; // end the string
        return final;
    }
    

    Working example: http://codepad.org/dd2w5cuy

提交回复
热议问题