-
Splitting
I've read the tutorials, read other peoples source code, and they all do more than I'm looking for which helps to my confusion, all i'm basically looking for is to split a string sentence, for example:
"An Example" would be split into 2 words, "An" and then the other "Example", most of you guys would be able to do this in seconds, but with the more I read on this, the more my head spins. If anyone would like to write an example to only split a sentence for me, I would be very grateful.
-
There are several solutions all depending on what data structure you use including array, string, and cstring. In the following solution, I use STL string.
-----
#include <vector>
#include <string>
using std::string;
std::vector<string> myWords;
string mySentence("A sentense");
string::size_type begPos = 0,
endPos = 0;
endPos = mySentence.find(' ', begPos);
while (endPos != string::npos)
{
myWords.push_back(mySentence.substr(begPos, endPos);
begPos = ++endPos;
endPos = mySentence.find(' ', begPos);
}
-----
Note the algorithm above may have minor bugs. Look it over and modify it to according to your needs.
Kuphryn
-
if you don't want to use stl classes you could use strtok() using space as the delimiter or devise your own function.
Code:
char phrase[] = "An Example";
int length = strlen(phrase);
int i, j;
char temp[100];
j = 0;
for(i = 0; i < length; i++)
{
if(phrase[i] != ' ')
temp[j++] = phrase[i];
else
{
temp[j] = '\0';
//now do something with temp
cout << temp << endl;
j = 0;
}
}
-
oh yeah, since there is no space at the end of Example you need to add the following lines at the end of the for loop if you use my example:
temp[j] = '\0';
//do something with temp here, too.
cout << temp << endl;
-
Code:
char *split_sentence( char *fStr, char *bStr )
{
while( isspace( *fStr ) ) fStr++;
while( *fStr != '\0' ) {
if( *fStr == ' ' ) {
fStr++;
break;
}
*bStr++ = *fStr++;
}
*bStr = '\0';
while( isspace( *fStr ) ) fStr++;
return fStr;
}
To Use:
Code:
char Command[128];
Buffer = split_sentence( Buffer, Command );
if u need to split CStrings, one other way not mentioned yet would be to use the c_str() function.
Code:
char * Buffer = new char[ txtLastCommand->Text.Length() + 1 ];
strcpy( Buffer, txtLastCommand->Text.c_str() );
Buffer = split_sentence( Buffer, Command );
Hope it helps.