473,661 Members | 2,502 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Trying to tokenize a string

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 )
{
//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

thanks!
Jul 19 '05 #1
9 18423
"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 )
{
//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

JePererTomCiy

That output doesn't make any sense, unless you mis-typed it... <?>
Jeremy

Jul 19 '05 #2


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.
#include <stdio.h>
#include <string.h>
int main()
{
char *mystring = "Jane and Peter and Tom and Cindy";
char *delim = " and ";
char *head;
char *tail;
char buf[80];
bool flag = true;

size_t len = strlen (delim);

head = mystring;

while (flag)
{
buf[0] = 0;

if ((tail = strstr (head, delim)) == 0)
{
strcpy (buf, head);
flag = false;
}
else
{
strncat (buf, head, tail-head);
head = tail + len;
}

puts (buf);
}

return 0;
}

Result:

Jane
Peter
Tom
Cindy

I don't recommend doing it this way, of course.


Brian Rodenborn
Jul 19 '05 #3
sw
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.

try something like this :

char mystring[] = "Jane and Peter and Tom and Cindy";
char *delim = " "; // only blank
char *token;

token = strtok(mystring , delim);

while (token !=NULL)
{
//compare ... (strcmp (token,"and") )
//continue loop if equal
cout << token << endl;
token = strtok(NULL,del im)
}


"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 )
{
//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

thanks!

Jul 19 '05 #4
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

Jul 19 '05 #5


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
Jul 19 '05 #6
Here is what I ended up doing using std::string

string line = "Tom and Peter and Jane and Joe and Bill";
string newline;

cout << "Before: " << line << endl;
std::string::si ze_type pos = 0;
std::string delim = " and ";
std::string newdelim = "\n";

while (( pos = line.find(delim ,pos ) ) != std::string::np os )
{
line.replace(po s, delim.length(), newdelim);
pos +=newdelim.leng th();
}
cout << "After: " << line << endl;
--------------------------------------------------------------

"Default User" <fi********@com pany.com> wrote in message
news:3F******** *******@company .com...


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

Jul 19 '05 #7

"lredmond" <lr******@nyc.r r.com> wrote in message
news:Ph******** *********@twist er.nyc.rr.com.. .
Here is what I ended up doing using std::string

string line = "Tom and Peter and Jane and Joe and Bill";
string newline;

cout << "Before: " << line << endl;
std::string::si ze_type pos = 0;
std::string delim = " and ";
std::string newdelim = "\n";

while (( pos = line.find(delim ,pos ) ) != std::string::np os )
{
line.replace(po s, delim.length(), newdelim);
pos +=newdelim.leng th();
}
cout << "After: " << line << endl;
--------------------------------------------------------------


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.

john

Jul 19 '05 #8
"Jeremy Cowles" <je************ *************@a sifl.com> wrote in message news:<Wi******* **************@ twister.tampaba y.rr.com>...
"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 )
{
//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
JePererTomCiy

That output doesn't make any sense, unless you mis-typed it... <?>


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

Jul 19 '05 #9

"Mike Wahler" <mk******@mkwah ler.net> wrote in message
news:be******** **@slb9.atl.min dspring.net...
| Lans <lr******@bn.co m> wrote in message
| news:19******** *************** **@posting.goog le.com...

[snip]

| /* 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 */

Hey Mike.

Anyone would think you were a 'C' programmer :-).

Cheers.
Chris Val
Jul 19 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

16
2290
by: qwweeeit | last post by:
In analysing a very big application (pysol) made of almost 100 sources, I had the need to remove comments. Removing the comments which take all the line is straightforward... Instead for the embedded comments I used the tokenize module. To my surprise the analysed output is different from the input (the last tuple element should exactly replicate the input line) The error comes out in correspondance of a triple string.
4
3120
by: Kelvin | last post by:
hi: in C, we can use strtok() to tokenize a char* but i can't find any similar member function of string that can tokenize a string so how so i tokenize a string in C++? do it the C way? thanks -- { Kelvin@!!! }
2
31375
by: James | last post by:
Hi, I am looking for a stringtokenizer class/method in C#, but can't find one. The similar classes in Java and C++ are StringTokenizer and CStringT::tokenize respectively. I need to keep a current position within the string and change the delimiters dynamically when going throught the string. Does anyone know a stringtokenizer in c#? Thanks a lot,
5
7172
by: Lam | last post by:
Hi I try to read in a line from text file, and how can I tokenize the line? Thanks
20
17209
by: bubunia2000 | last post by:
Hi all, I heard that strtok is not thread safe. So I want to write a sample program which will tokenize string without using strtok. Can I get a sample source code for the same. For exp: 0.0.0.0--->I want to tokenize the string using delimiter as as dot. Regards
1
2273
by: Tim | last post by:
I ran into a problem with a script i was playing with to check code indents and need some direction. It seems to depend on if tabsize is set to 4 in editor and spaces and tabs indents are mixed on consecutive lines. Works fine when editors tabsize was 8 regardless if indents are mixed. Below are how the 3 test files are laid out, the sample code and output I get. Any help on how to detect this correctly would be appreciated.
0
2177
by: noobcprogrammer | last post by:
#include "IndexADT.h" int IndexInit(IndexADT* word) { word->head = NULL; word->wordCount = 0; return 1; } int IndexCreate(IndexADT* wordList,char* argv)
2
2531
by: askalottaqs | last post by:
there's in maya's scripting language mel, called tokenize, you simply tokenize("string i want to tokenize"," ",bufferArray) which will fill the fufferArray wih the first string tokenized accorfing to the second string, isnt there anything as staight forward as this in c++?
6
4235
m6s
by: m6s | last post by:
1. After hours of researching, I used these snippets : void Object::TokenizeLines(const string& str, vector<string>& tokens, const string& delimiters) // Skip delimiters at beginning. string::size_type lastPos = str.find_first_not_of(delimiters, 0); // Find first "non-delimiter". string::size_type pos = str.find_first_of(delimiters, lastPos); while (string::npos != pos || string::npos != lastPos) { // Found a token, add it...
1
8545
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8633
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6185
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5653
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4179
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4346
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2762
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1986
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1743
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.