Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing spaces and special characters from string

Tags:

c

string

How do you remove spaces and special characters from a string?

I couldn't find a single answer while googling. There were a lot related to other languages, but not C. Most of them mentioned the use of regex, which isn't C standard (?).

Removing a simple space is easy:

 char str[50] = "Remove The Spaces!!";

Then a simple loop with a if-statement:

if (str[i] != ' ');

Output would be:

RemoveTheSpaces!!

What do I add to the if-statement so it would recognize special characters and remove them?

My definition of special characters:

Characters not included in this list: 
A-Z a-z 0-9
like image 850
dertzi Avatar asked Oct 18 '25 06:10

dertzi


2 Answers

This is probably not the most efficient way of achieving this but it will get the job done fairly fast.

Note: this code does require you to include <string.h> and <ctype.h>

char str[50] = "Remove The Spaces!!";
char strStripped[50];

int i = 0, c = 0; /*I'm assuming you're not using C99+*/
for(; i < strlen(str); i++)
{
    if (isalnum(str[i]))
    {
        strStripped[c] = str[i];
        c++;
    }
}
strStripped[c] = '\0';

Using your if statement:

if (str[i] != ' ');

With a little logic (the characters have to be in the range a-z or A-Z or 0-9:

If ( !('a' <= str[i] && 'z' >= str[i]) &&
     !('A' <= str[i] && 'Z' >= str[i]) &&
     !('0' <= str[i] && '9' >= str[i])) then ignore character.
like image 41
George Mitchell Avatar answered Oct 19 '25 19:10

George Mitchell