Overclock.net banner

1 - 5 of 5 Posts

·
Registered
Joined
·
1,984 Posts
Discussion Starter #1
I need a code snippet that will remove all non-alphanumeric characters from a string, and then put each word into a vector seperately. So far

Pseudo code

Code:
Code:
for (i = 0; i < string.size(); i++){
  prev = i
  if(nonAlphanum(string[i]){
    vector.push_back(string.substr(prev,i-1)
    prev = i
  }
}
and nonAlphanumeric would just do a char to char comparison of all letters/numbers to string

is that any good? or is there a more efficient way to do this, as well i think my counters might be a lil off, but i just drew this up real quick for help
 

·
Premium Member
Joined
·
4,616 Posts
Sir, may I offer to you...

REGULAR EXPRESSIONS.

They're really confusing but this will work perfectly for you (if you can figure it out)
 
  • Rep+
Reactions: im_not_an_artard

·
Banned
Joined
·
2,461 Posts
Code:

Code:
char[] src = "This is my 66 string !#$#@!,.,";
char dest[64];
unsigned long sptr, dptr;
sptr = dptr = 0;

while (src[sptr])
{
    if (src[sptr] >= 'a' && src[sptr] <= 'z') dest[dptr++] = src[sptr];
    else if (src[sptr] >= 'A' && src[sptr] <= 'Z') dest[dptr++] = src[sptr];
    else if (src[sptr] >= '0' && src[sptr] <= '9') dest[dptr++] = src[sptr];
    sptr++;
}
edit-Just read your full post haha. Well, this loop will copy each character one by one if it's alphanumeric, and skip over it if it's not. You can just add a line to check for a space ' ', and if it's a space, start copying the src string to a new dest string, then each word will not only be stripped but in it's own string array location.
 

·
Premium Member
Joined
·
2,687 Posts
Quote:


Originally Posted by Kuntz
View Post

Code:
Code:
char[] src = "This is my 66 string !#$#@!,.,";
char dest[64];
unsigned long sptr, dptr;
sptr = dptr = 0;

while (src[sptr])
{
    if (src[sptr] >= 'a' && src[sptr] <= 'z') dest[dptr++] = src[sptr];
    else if (src[sptr] >= 'A' && src[sptr] <= 'Z') dest[dptr++] = src[sptr];
    else if (src[sptr] >= '0' && src[sptr] <= '9') dest[dptr++] = src[sptr];
    sptr++;
}
edit-Just read your full post haha. Well, this loop will copy each character one by one if it's alphanumeric, and skip over it if it's not. You can just add a line to check for a space ' ', and if it's a space, start copying the src string to a new dest string, then each word will not only be stripped but in it's own string array location.

In the cctype library you can use the function isalnum() which checks if its input char is alphanumeric and returns 1 if it is, 0 otherwise.

Code:
Code:
#include <cctype>

char[] src = "This is my 66 string !#$#@!,.,";
char dest[64];
unsigned long sptr, dptr;
sptr = dptr = 0;

while (src[sptr])
{
    if (isalnum(src[sptr])) 
        dest[dptr] = src[sptr];
    ++dptr;
    ++sptr;
}
 
1 - 5 of 5 Posts
Top