Lans <lr******@bn.co m> wrote in message
news:19******** *************** **@posting.goog le.com...
I have a string that I need to tokenize but I need to use a string
token
see example i am trying the following but strtok only uses characters
as delimiters and I need to seperate bu a certain word
char *mystring "Jane and Peter and Tom and Cindy"
char *delim = " and ";
char *token;
token = strtok(mystring , delim);
while (token !=NULL )
{
file://do some work
cout << token << endl;
token = strtok(NULL,del im)
}
my output would return JePererTomCiy
I need my output to be Jane Peter Tome Cindy
How can I accomplish this output
First, I'd use a 'std::string' object instead of
an array of characters.
The code below accomodates either a character array
or a std::string.
#include <algorithm>
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>
typedef std::istream_it erator<std::str ing> istrit;
typedef std::ostream_it erator<std::str ing> ostrit;
std::string xfrm(const std::string& s)
{
return s == "and" ? "" : s + ' ';
}
/* void replace_delims( std::string& s) */
/* -- modifies argument 's' as follows: */
/* */
/* - Removes all occurrences of the string "and" which are */
/* delimited by whitespace and/or end-of-string */
/* */
/* - Replaces consecutive whitespace characters with a */
/* single space character */
/* */
/* - Removes leading and trailing whitespace */
void replace_delims( std::string& s)
{
std::ostringstr eam oss;
std::transform( istrit(std::ist ringstream(s)), istrit(),
ostrit(oss), xfrm);
const std::string& ref = oss.str();
s = ref.substr(0, ref.size() - !ref.empty());
}
/* void replace_delims( char* s) */
/* -- Same as 'void replace_delims( std::string&)', */
/* but operates on a 'C-style string' */
void replace_delims( char *s)
{
std::string result(s);
std::string::si ze_type sz(result.size( ));
replace_delims( result);
std::copy(resul t.begin(), result.begin() + sz, s);
s[sz] = 0;
}
int main()
{
char mystring[] = "Jane and Peter and Tom and Cindy";
std::cout << "Before:\n" << '#' << mystring << '#' << "\n\n";
replace_delims( mystring);
std::cout << "After: \n" << '#' << mystring << '#' << "\n\n";
return 0;
}
Output:
Before:
#Jane and Peter and Tom and Cindy#
After:
#Jane Peter Tom Cindy#
-Mike