Advertisements

Lans wrote:
>
> 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

If you are dead set on using C-style strings instead of C++ std::string
class, then the best way is probably to use strstr(). Here's an example,
written almost completely in C (except for the bool). Note that no
precaution for overrun of buf[] is taken, it's done by inspection for
this problem.

It looks as if you misunderstood what the <<char*delim>> does
You tokenized the string with delimiting chars ' ','a','n','d',' '
to something like "J\n" "e\n" "Pe\n" later you put them into std::cout
without spaces.
Delimiters are single characters, not strings.

The solution I gave you WAS C++, it's just adapted from a C program I
wrote. If you are going to use char * types, that's all you need. If you
are going to use std::string, then there are other solutions. Read up on
them, take a stab, post your code.

"Default User" <> wrote in message
news:...
>
>
> lredmond wrote:
> >
> > Can you give me a C++ example.
>
> Don't top-post.
>
> The solution I gave you WAS C++, it's just adapted from a C program I
> wrote. If you are going to use char * types, that's all you need. If you
> are going to use std::string, then there are other solutions. Read up on
> them, take a stab, post your code.
>
>
>
>
> Brian Rodenborn

Its not the most efficient since you repeatedly hack the same string. It
probably better to build up your output string as a completely seperate
string, copying over everything from the original string except the
delimiters.

strtok writes a null character '\0' at the end of each token, and
takes tokens to be seperated by sequences of ' ', 'a', 'n' and 'd'
characters.
So, the first token is 'J', since the "an" after it is a delimiter
sequence.
The 'J' is null-terminated by strtok writing '\0' over the 'a', and
duly printed.
The next token returned is "Peter" (I assume the "Perer" was a typo).
The null terminator is written over the following space character, and
the token is printed.

.... and so on.
This clearly isn't what the author wanted, but the output looks
plausible for the code.
>
> Jeremy

Share This Page

Welcome to The Coding Forums!

Welcome to the Coding Forums, the place to chat about anything related to programming and coding languages.

Please join our friendly community by clicking the button below - it only takes a few seconds and is totally free. You'll be able to ask questions about coding or chat with the community and help others.
Sign up now!