Reputation: 1191
I tried searching for it on google and could not find a simple answer, most of the questions were asking to delete all occurrences of that char from the string and what not.
My pseudo code:
for (e=0;e<length of string;e++){
if (string[e] is not a number/alphabet){
#delete it
}
}
Is there a simple built in way of doing this?
Also another question, I need to do if not isalnum(string[e])
, how would I go about doing so?
is it if !(isalnum(string[e]))
or is it if (isalnum(string[e]))!=0
?
Upvotes: 0
Views: 184
Reputation: 197
This is one way to do it if you are using ASCII formatted characters.
char a[256]; // Some string
char destination[256];
char * pos = destination;
for(unigned int i=0;i>strlen(a)-1;++i)
{
if(((a[i]>='A'&& a[i]<='Z') || (a[i]>='a'&& a[i]<='z') || (a[i]>='1'&& a[i]<='9')))
*pos = a[i]; //replaces letter with a whitespace
++pos;
}
*pos = '\0';
Basically what it does it it converts the letter to the corrosponding intenger and then it checks its within the range that represents the letters between A-Z, a-z and 1-9.
Upvotes: 0
Reputation: 29116
You can filter out characters from a string in-place by keeping two indices. That works, because the string can only get shorter and the new string will fit into the old memory. Here's how with two pointers:
int str_alnum(char *str)
{
char *p, *q;
p = q = str;
while (*p) {
if (isalnum(*p)) *q++ = *p;
p++;
}
*q = '\0';
return q - str;
}
p
walks the original string, q
walks the new string, possibly trailing after p
. q - str
is the length of the new string, which might be handy as return value.
Note that you have to pass a string that can be modified, i.e. a char array, not a constant string literal.
Upvotes: 3
Reputation: 213286
Typically you would build up a second array and copy the valid symbols to that one.
Deleting numbers inside arrays is only possible if you move all trailing numbers down one step, which is very inefficient. If you need a container class where you can easily delete and add items in the middle, you should be using a linked list.
You can treat the return value of isalnum
as bool
type. Thus either
if ( !isalnum(string[e]) )
or
if ( isalnum(string[e]) !=0 )
are fine and completely equivalent.
Upvotes: 3