famedoro
famedoro

Reputation: 1241

Remove special char from string in C under Linux

Using C in Linux, how can I remove character (or any other "specific" non ASCII character - passed as a parameter to the function -) from a string?

I have tried with:

void remove_all_chars(char* str, char c) {
    char *pr = str, *pw = str;
    while (*pr) {
        *pw = *pr++;
        pw += (*pw != c);
    }
    *pw = '\0';
}

but I get:

:warning: multi-character character constant.

Should I convert before the string in wide char something like

wchar_t wsAux[100];
remove_all_chars(wsAux, "A€bcd", 100);

but it doesn't work.

Upvotes: 1

Views: 1934

Answers (3)

famedoro
famedoro

Reputation: 1241

I've tried:

void removeSubstring(char *s,const char *toremove)
{
  while( s=strstr(s,toremove) )
   memmove(s,s+strlen(toremove),1+strlen(s+strlen(toremove)));
}

from Removing substring from a string? and it works.

In this way then € symbol is treated as string, in fact it occupy 3 bytes ( try strlen("€") )!

Upvotes: 0

user207064
user207064

Reputation: 665

Try This

#include<stdio.h>
void remove_all_chars(char* str) {
    char *pr = str, *pw = str;
    while (*pr) {
    if(isascii(*pr))
    {
        //printf("%c: is ascii char \n", *pr);
        *pw = *pr;
        pw++;
    }
    pr++;
    }
    *pw = '\0';
}

main()
{

    char str[100] = "asÄ—df";
    remove_all_chars(str);
    printf("%s\n",str);

}

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409472

I guess you are doing something like

remove_all_chars(some_string, 'A€bcd');

Note that you are using multiple characters in a character literal. This is not allowed, except as an extension to the compiler. And most likely will not work as you expect.

Instead pass the characters you want to remove as a string:

remove_all_chars(some_string, "A€bcd");

Of course with the proper modification to the remove_all_chars function.

Upvotes: 0

Related Questions