I'm attempting to remove a character from a string in C. The problem I am having with my code is that it removes the first instance of the character from the string but also wipes everything after that character in the string too. For example, removing 'l' from 'hello' prints 'he' rather than 'heo'
int i; char str1[30] = "Hello", *ptr1, c = 'l'; ptr1 = str1; for (i=0; i<strlen(str1); i++) { if (*ptr1 == c) *ptr1 = 0; printf("%c\n", *ptr1); ptr1++; }
I need to use pointers for this and would like to keep it as simple as possible since I'm a beginner in C. Thanks
Logic to remove all occurrences of a characterRun a loop from start character of str to end. Inside the loop, check if current character of string str is equal to toRemove. If the mentioned condition is true then shift all character to one position left from current matched position to end of string.
We can use string replace() function to replace a character with a new character. If we provide an empty string as the second argument, then the character will get removed from the string.
To remove everything after a specific character in a string:Use the String. split() method to split the string on the character. Access the array at index 0 . The first element in the array will be the part of the string before the specified character.
We can also use the split() method to remove all the occurrences of a character from a given string. The split() method, when invoked on a string, takes a separator as its input argument.
You can do it like this:
void remove_all_chars(char* str, char c) { char *pr = str, *pw = str; while (*pr) { *pw = *pr++; pw += (*pw != c); } *pw = '\0'; } int main() { char str[] = "llHello, world!ll"; remove_all_chars(str, 'l'); printf("'%s'\n", str); return 0; }
The idea is to keep a separate read and write pointers (pr
for reading and pw
for writing), always advance the reading pointer, and advance the writing pointer only when it's not pointing to a given character.
If you remove the characters in place you will have to shift the rest of the string one place to the left every time you remove a character, this is not very efficient. The best way is to have a second array that takes the filtered string. For example you can change your code like this.
int i; char str1[30] = "Hello", *ptr1, c = 'l'; char str2[30] = {0}, *ptr2; ptr1 = str1; ptr2 = str2; for (i=0; i<strlen(str1); i++) { if (*ptr1 != c) *ptr2++=*ptr1; ptr1++; } printf("%s\n", str2);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With