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 als
The problem is that when you encounter the first character that matches c
, you insert a null character right there. That means you're essentially cutting off the rest of the string.
What you need to do is when you find a matching character, move the following characters back one position. Then you need to insert the null character at the very end depending on how many characters you have removed.
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.
C defines a string as "a contiguous sequence of characters terminated by and including the first null 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);
i know that it is a type of duplicate answer, but this code is function's version for solving the problem. I thought that as the questioner was a beginner, he might learn much from decomposed version of problem.
int del_x_char(char *p, int x)
{
char *q;
x=first_occurance(p, 'i')/*you can replace any character that you want delete with 'i'*/
q=p+x;
while(*q=*(q+1))
q++;
*q='\0';
return 0;
}
int first_occurance(char *q, char phar)
{
int i=0;
while(*q)
{
if(*q++==phar)
return i;
i++;
}
return -1;
}
char str1[30] = "Hello", *prt1, c = 'l';
char str2[30], *prt2;
prt1 = str1;
prt2 = str2;
while(*prt1 != 0)
{
if(*prt1 != c)
{
*prt2 = *prt1;
prt2++;
}
prt1++;
}
*prt2 = '\0';