after i use the getline function to get a phrase. Now how do i break the phrase into words ?
Printable View
after i use the getline function to get a phrase. Now how do i break the phrase into words ?
there's easier ways, but you could walk the string and look for spaces... then break those up into their own strings...
but how do i do it ?
when i encounter the 2nd space, how i know the length between the 1st space and the 2nd space ?
a space is one character... one element in the array... just write something like this:this will put the words (tokens) in it's own array... actually, in this case, an array of arrays... it would look like this:Code:...
int count=0;
int x=0;
int y=0;
int someleft=strlen(phrase);
while(count<someleft)
{
if(phrase[count]!=' ')
{
token[y][x]=phrase[count];
x++;
}
else
{
x=0;
y++;
}
count++;
}
...
like I said, I think there's better ways than this, so you may want to wait around for a better response, but this is the way I would do it (because it's the only way I know how)... I'm not sure the code I gave you works either, but you should be able to get the general idea from it...Code:input: The Quick Brown Fox
token[0]:The
token[0][0]:T
token[0][1]:h
token[0][2]:e
token[1]:Quick
token[2]:Brown
token[3]:Fox
unless you mean there's several spaces... like something like this:in that case, my code would still work, but inefficiently... it would look more like this:Code:The Quick Brown Fox
at least that's what I think it will do... but like I said, I didn't check the actual code... I would wait for a better response if I were you... I should probably learn some better ways too... or you could try something with isspace(), like this:Code:token[0]:The
token[1]:
token[2]:
token[3]:
token[4]:
token[5]:
token[6]:
token[7]:
token[8]:
token[9]:
token[10]:
token[11]:Quick
token[12]:
token[13]:Brown
token[14]:
...
token[56]:fox
that might fix the problem with multiple spaces... jeebus... this post is getting a little too long for it's own good...Code:...
int count=0;
int x=0;
int y=0;
int someleft=strlen(phrase);
bool new;
while(count<someleft)
{
if(phrase[count]!=' ')
{
token[y][x]=phrase[count];
x++;
new=true;
}
else if(new)
{
x=0;
y++;
new=false;
}
else
x++;
count++;
}
...
I wouldn't use new as variable name, it's a keyword.
You can use string_tokenizer from the boost library.
But in this case I suppose it would be simpler to use >> for string input in the first place, so that the stream does the splitting for you. Except that makes you miss the breaking character. Hmm...
yeah... I missed that... and you can't use new as a variable name... heh... I actually started writing that as psuedo-code, but then decided to just write some dummy code...
I always say pseudo-code is evil ;)
Then stay on your side of the fence. I find it extremely useful.Quote:
Originally posted by CornedBee
I always say pseudo-code is evil ;)
;) back
:)