How to replace certain characters in a string with other characters

I am trying to make a program that takes a string as an input string and replaces all vowels with *. So, for "hello world" star_vowels should return "h * ll * w * rld".

So far I have the code:

int star_vowels(char s[]){ int j; j = 0; while (s[j] != '0'){ j++; if (s[j] = 'a' || s[j] == 'e' || s[j] == 'i' || s[j] == 'o' || s[j] == 'u'){ putchar('*'); } else { putchar(j); } return 0; } } 
+4
source share
3 answers

This code has a number of errors.

1) while (s[j] != '0') I'm sure you want to check the NUL character, not the constant character. Change '0' to '\0'

2) j++ you increment j before you even look at the 0th index of your array. If you have a vowel at s [0], this will be skipped. Move j++ to the very bottom of the while loop, before the ending bracket.

3) s[j] = 'a' You use the assignment operator = here, when instead you must use the equality operator == . Using an assignment operator is legal C code and thus will compile. Unfortunately, it will return true, and you will eventually replace all your characters with asterisks

4) putchar(j); You are trying to output 'j' (your iterator) when you really want to output s [j] (your character).

5) return 0 as in # 2, your return statement is in the wrong place. You have this inside a while loop when it should be outside of it. As you wrote it, the while loop will only perform the first iteration before your function goes out of scope.

 int star_vowels(char s[]) { int j = 0; while (s[j] != '\0'){ if (s[j] == 'a' || s[j] == 'e' || s[j] == 'i' || s[j] == 'o' || s[j] == 'u') { putchar('*'); } else { putchar(s[j]); } j++; } return 0; } 
+6
source

I think your question will be "everything is there" and that because of this part of your giant if :

if (s[j] = 'a'

That will always be true. You will need ==

You also put j++ too early - you skip characters, because you immediately increase when you enter the loop.

+4
source

By increasing j at the beginning, you lose index 0 (first character).

Since you want to return new data to the outside world (outside the scope of functions), you either allocate memory for new data outside the function, or pass a pointer to this data to this function, or simply allocate dynamic memory inside this function - do not forget to delete it.

One implementation:

 char *star_vowels(char s[]){ // let 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

+2
source

All Articles