Reputation: 89
I'm trying to remove the vowels from the userInput array and copy the rest to the newString array. I thought looping through the userInput and assigning it to newStrin would work but im only getting the first character of newString array. I can see that on the iteration where i = 2, 't' should be assigned to newString[2] but when I attempt to print the array back in main it only prints the first character.
void removeVowels( char newString [], char userInput []){
int i = 0;
while ( i < myStrlen(userInput)) {
if ( (userInput[i] != 'a')&&
(userInput[i] != 'e')&&
(userInput[i] != 'i')&&
(userInput[i] != 'o')&&
(userInput[i] != 'u')){
newString[i] = userInput[i];
cout << newString[i] << endl;
}
i++;
}
}
My output:
c
t
cat without vowels is: c
Expected output:
c
t
cat without vowels is: ct
Upvotes: 3
Views: 225
Reputation: 11430
The only part you are missing is keeping track of the place to write at
int writePos = 0;
Then, to replace newString[i] = userInput[i];
with newString[writePos++] = userInput[i];
which will write at the right place, then increment the position.
And then, fix the cout
accordingly.
As @SalehMostafa points out, you should null-terminate the string, too, otherwise the caller will be reading garbage at the end.
newString[writePos] = 0; // at the end before returning
Upvotes: 4
Reputation: 483
in Modern C++
string s = "my lovely cat is jumping in the kitchen again";
auto r = std::remove_if( s.begin(), s.end(), [](auto x) {
return "aeiou"s.find(x) != std::string::npos;
} );
s.erase(r, s.end());
[my lvly ct s jmpng n th ktchn gn]
Upvotes: 1