473,787 Members | 2,932 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

parse comma delimited text string

in MS VC++ Express I need to know how to get from one comma delimited
text string to many strings.

from this:

main_string = "onE,Two,Th ree , fouR,five, six "

to these:

string1 = "one"
string2 = "two"
string3 = "three"
string4 = "four"
string5 = "five"
string6 = "six"

the white space needs to be removed and the case needs to be all upper
or lower.
The result needs to be strings and not pointers or addresses in memory
so I can test:

string test = "three";

if (three == "three")

some getlines will only have two strings some may have up to 10
Please help with examples, you input with exact syntax is greatly
appreciated

I have been struggling with not using pointers but every time I end up
using them.

Thanks in advance

Feb 7 '06 #1
25 31799
electrixnow wrote:
in MS VC++ Express I need to know how to get from one comma delimited
text string to many strings.

from this:

main_string = "onE,Two,Th ree , fouR,five, six "

to these:

string1 = "one"
string2 = "two"
string3 = "three"
string4 = "four"
string5 = "five"
string6 = "six"
For this, a couple of options are the good old C strtok, or the
std::string find members.
the white space needs to be removed and the case needs to be all upper
or lower.


See toxxxx() and isxxx() functions.

Looks too much like homework to me...

--
Ian Collins.
Feb 7 '06 #2
Howework, not even close. I am an 42 year old EE and not really a
programmer. I have an application at work to apply this to. I am trying
to compare two data files and create a third to let my department know
when new releases for drawing are ready. I have tried strtok, and
strtok_s but those functions allways create pointers. That is fine if I
knew how to easly change them back to STRINGS for string comparison. By
the way we have the same last name, that's wierd.

been out of school for too many years!

The only coding I have done was born, corn and c shell in the 80's. C++
is so much more robust, I am trying to learn more. I just purchased a
book C++ without fear. If you have any suggestions for books for VC++
let me know.

what is the best way to compare text strings like this:

if ( "test string" == pointer_returne d_from_strtok )

that will get me going in the right directions.

Thanks!

Feb 7 '06 #3
electrixnow wrote:
Howework, not even close. I am an 42 year old EE and not really a
programmer. I have an application at work to apply this to. I am trying
to compare two data files and create a third to let my department know
when new releases for drawing are ready. I have tried strtok, and
strtok_s but those functions allways create pointers. That is fine if I
knew how to easly change them back to STRINGS for string comparison. By
#include <string>
#include <iostream>

int main() {
// C style string
char mystring[] = "hello world";

// pointer to null terminated token
char* token = mystring + 6;

// create string from token
std::string newString(token );

if (newString == "world") {
std::cout << "Comparison True" << std::endl;
} else {
std::cout << "Comparison Fasle" << std::endl;
}
}
The only coding I have done was born, corn and c shell in the 80's. C++
is so much more robust, I am trying to learn more. I just purchased a
book C++ without fear. If you have any suggestions for books for VC++
let me know.
Accelerated C++, by Koenig and Moo.
what is the best way to compare text strings like this:

if ( "test string" == pointer_returne d_from_strtok )
// create string on the fly
if ("test string" == std::string(poi nter_returned_f rom_strtok))
that will get me going in the right directions.


Off you go then! :)

Ben Pope
--
I'm not just a number. To many, I'm known as a string...
Feb 7 '06 #4
* electrixnow:
in MS VC++ Express I need to know how to get from one comma delimited
text string to many strings.

from this:

main_string = "onE,Two,Th ree , fouR,five, six "

to these:

string1 = "one"
string2 = "two"
string3 = "three"
string4 = "four"
string5 = "five"
string6 = "six"

the white space needs to be removed and the case needs to be all upper
or lower.
The result needs to be strings and not pointers or addresses in memory
so I can test:

string test = "three";

if (three == "three")

some getlines will only have two strings some may have up to 10
Please help with examples, you input with exact syntax is greatly
appreciated

I have been struggling with not using pointers but every time I end up
using them.


std::string uppercase( std::string const& s )
{
std::string result = s;
for( std::size_t i = 0; i < s.length(); ++i )
{
result[i] = static_cast<cha r>( std::toupper( s[i] ) );
}
return result;
}

typedef std::vector<std ::string> StringVector;

StringVector stringsFrom( std::string s )
{
std::replace( s.begin(), s.end(), ',', ' ' );
std::istringstr eam stream( s );
StringVector result;
for( ;; )
{
std::string word;
if( !( stream >> word ) ) { break; }
result.push_bac k( uppercase( word ) );
}
return result;
}

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Feb 7 '06 #5

"electrixno w" <info...@charte r.net> wrote in message
news:11******** *************@g 47g2000cwa.goog legroups.com...
in MS VC++ Express I need to know how to get from one comma delimited
text string to many strings.

from this:

main_string = "onE,Two,Th ree , fouR,five, six "


You could try something like this:
#include <string>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <cctype>
void trim(std::strin g& str)
{
std::string::si ze_type idx = str.find_first_ not_of(' ');
if (idx != std::string::np os) {
str.erase(0, idx);
}
idx = str.find_last_n ot_of(' ');
if (idx != std::string::np os) {
str.erase(idx+1 , str.size()-1);
}
}

int main()
{
std::string main_string = "onE,Two,Th ree , fouR,five, six ,,
d, , ";

std::istringstr eam iss(main_string );
std::string tok;

while (getline(iss, tok, ',')) {
std::transform( tok.begin(), tok.end(), tok.begin(),
std::tolower);
trim(tok);
std::cout << '!' << tok << "!\n";
}
}

Regards,
Sumit.
--
Sumit Rajan <su****@msdc.hc ltech.com>
Feb 7 '06 #6

"Sumit Rajan" <su*********@gm ail.com> wrote in message
news:44******** ****@individual .net...
void trim(std::strin g& str)
{
std::string::si ze_type idx = str.find_first_ not_of(' ');
if (idx != std::string::np os) {
str.erase(0, idx);
}
idx = str.find_last_n ot_of(' ');
if (idx != std::string::np os) {
str.erase(idx+1 , str.size()-1);
}
}


Sorry, this function has a bug. May be simplest to use an std::istringstr eam
as you will see in Alf's post.

Sumit.
--
Sumit Rajan <su****@msdc.hc ltech.com>
Feb 7 '06 #7

"Sumit Rajan" <su*********@gm ail.com> wrote in message
news:44******** ****@individual .net...
void trim(std::strin g& str)
{
std::string::si ze_type idx = str.find_first_ not_of(' ');
if (idx != std::string::np os) {
str.erase(0, idx);
}
idx = str.find_last_n ot_of(' ');
if (idx != std::string::np os) {
str.erase(idx+1 , str.size()-1);
}
}


void trim(std::strin g& str)
{
while((!str.emp ty()) && isspace(str[0])) {
str.erase(0, 1);
}
std::string::si ze_type idx = str.find_last_n ot_of(' ');
if (!((idx == std::string::np os)||(idx == str[str.size()-1]))) {
str.erase(idx+1 , str.size()-1);
}
}

Regards,
Sumit.
--
Sumit Rajan <su****@msdc.hc ltech.com>
Feb 7 '06 #8
In article <11************ *********@g47g2 000cwa.googlegr oups.com>,
"electrixno w" <info...@charte r.net> wrote:
in MS VC++ Express I need to know how to get from one comma delimited
text string to many strings.

from this:

main_string = "onE,Two,Th ree , fouR,five, six "

to these:

string1 = "one"
string2 = "two"
string3 = "three"
string4 = "four"
string5 = "five"
string6 = "six"

the white space needs to be removed and the case needs to be all upper
or lower.
The result needs to be strings and not pointers or addresses in memory
so I can test:

string test = "three";

if (three == "three")

some getlines will only have two strings some may have up to 10
Please help with examples, you input with exact syntax is greatly
appreciated

I have been struggling with not using pointers but every time I end up
using them.

Thanks in advance


Assuming there are no spaces other than the ones just before or just
after the commas, the following will work:

template < typename Out >
void fn( string str, Out it )
{
int (*lower)(int) = &tolower;
transform( str.begin(), str.end(), str.begin(), lower );
replace( str.begin(), str.end(), ',', ' ' );
stringstream ss( str );
copy( istream_iterato r<string>( ss ), istream_iterato r<string>(),
it );
}

Call the above with a container that has the space or using a
back_inserter. For example:

vector<string> vec;
fn( main_string, back_inserter( vec ) );

The only magic is replacing the comma's with spaces so that the
stringstream will ignore them.
If there are spaces that must be saved then the above won't work. For
example:

main_string = "John Smith, Mark Allen ,Joe";

If the above needs to be parsed to:
vec[0] = "john smith"
vec[1] = "mark allen"
vec[2] = "joe"

Here we can't just dump the commas...

// returns a string that has had the whitespace at the front
// and back removed without disturbing the whitespace in the middle
string strip( string str )
{
const char* const whitespace = " \t";
str.erase( 0, str.find_first_ not_of( whitespace ) );
string::size_ty pe pos = str.find_last_n ot_of( whitespace );
if ( pos != string::npos )
str.erase( pos + 1 );
return str;
}

template < typename Out >
void foo( string str, Out it )
{
int (*lower)(int) = &tolower;
transform( str.begin(), str.end(), str.begin(), lower );
string::size_ty pe prev = 0;
for ( string::size_ty pe pos = str.find( ',' ); pos != string::npos;
pos = str.find( ',', prev ) )
{
string s = strip( str.substr( prev, pos - prev ) );
it++ = s;
prev = pos + 1;
}
string s = strip( str.substr( prev ) );
it = s;
}

--
Magic depends on tradition and belief. It does not welcome observation,
nor does it profit by experiment. On the other hand, science is based
on experience; it is open to correction by observation and experiment.
Feb 7 '06 #9
In article <po************ *************** ***@news.east.e arthlink.net>,
"Daniel T." <po********@ear thlink.net> wrote:
If there are spaces that must be saved then the above won't work. For
example:

main_string = "John Smith, Mark Allen ,Joe";

If the above needs to be parsed to:
vec[0] = "john smith"
vec[1] = "mark allen"
vec[2] = "joe"

Here we can't just dump the commas...

// returns a string that has had the whitespace at the front
// and back removed without disturbing the whitespace in the middle
string strip( string str )
{
const char* const whitespace = " \t";
str.erase( 0, str.find_first_ not_of( whitespace ) );
string::size_ty pe pos = str.find_last_n ot_of( whitespace );
if ( pos != string::npos )
str.erase( pos + 1 );
return str;
}

template < typename Out >
void foo( string str, Out it )
{
int (*lower)(int) = &tolower;
transform( str.begin(), str.end(), str.begin(), lower );
string::size_ty pe prev = 0;
for ( string::size_ty pe pos = str.find( ',' ); pos != string::npos;
pos = str.find( ',', prev ) )
{
string s = strip( str.substr( prev, pos - prev ) );
it++ = s;
prev = pos + 1;
}
string s = strip( str.substr( prev ) );
it = s;
}


I liked Sumit Rajan's use of getline... Modified my code to use it.

string& strip( string& str )
{
const char* const whitespace = " \t";
str.erase( 0, str.find_first_ not_of( whitespace ) );
string::size_ty pe pos = str.find_last_n ot_of( whitespace );
if ( pos != string::npos )
str.erase( pos + 1 );
return str;
}

template < typename Out >
void fn( string str, Out it )
{
int (*lower)(int) = &tolower;
transform( str.begin(), str.end(), str.begin(), lower );
stringstream ss( str );
string s;
while ( getline( ss, s, ',' ) )
it++ = strip( s );
}
--
Magic depends on tradition and belief. It does not welcome observation,
nor does it profit by experiment. On the other hand, science is based
on experience; it is open to correction by observation and experiment.
Feb 7 '06 #10

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

Similar topics

4
2822
by: Arne | last post by:
From: "Arne de Booij" <a_de_booij@hotmail.com> Subject: Comma delimited array into DB problems Date: 9. februar 2004 10:39 Hi, I have an asp page that takes input from a form on the previous page, puts that into an array and inserts the array into SQL server. Now here is the problem:
18
12344
by: MW | last post by:
Dear All Does anyone have a regular expression to parse a comma delimited line with some fields optionally having string delimiters (text qualifiers) I am currently testing with this regular expression and it works in almost all my test cases. I found this on the internet in a C# solution. ,(?=(*"*")*(?!*")) However in some of my test cases it fails and I am having difficulty
22
872
by: Ram Laxman | last post by:
Hi all, I have a text file which have data in CSV format. "empno","phonenumber","wardnumber" 12345,2234353,1000202 12326,2243653,1000098 Iam a beginner of C/C++ programming. I don't know how to tokenize the comma separated values.I used strtok function reading line by line using fgets.but it gives some weird behavior.It doesnot stripout the "" fully.Could any body have sample code for the same so that it will be helfful for my...
2
2015
by: Larry Williams | last post by:
Is there an easy way to convert a string of data to XML format without having to create the xml one field at a time? Sorry I'm a newbie and my xml knowledge is limited. I have tried to search through the documentation in .net but nothing jumps out at me. Sample code would be great!
9
4515
by: Wayne | last post by:
I have the following string: "smith", "Joe", "West Palm Beach, Fl." I need to split this string based on the commas, but as you see the city state contains a comma. String.split will spilt the city state. Is there a built in function that I'm missing that will do the split and recognize that the comma in city state is part of the item? --
5
2719
by: Yama | last post by:
Hi, I am looking to create a report comma delimited on a click of a button. Explanantion: 1. Get from the database: "SELECT * FROM Customers WHERE Region = 'CA'" 2. Use either DataReader or DataSource 3. Create a button "Export" 4. On ServerClick Event prompt user to save as a text comma delimited file.
2
2135
by: Ron | last post by:
so if my textbox is named textbox1 and my listbox is named ltsdisplay, for the button that would make this all happen I would just need to: lstdisplay.items.textbox1(delimited.Split(",".ToCharArray())) is that right? or no? I try this and I get an error...
5
64652
AdrianH
by: AdrianH | last post by:
Assumptions I am assuming that you know or are capable of looking up the functions I am to describe here and have some remedial understanding of C++ programming. FYI Although I have called this article “How to Parse a File in C++”, we are actually mostly lexing a file which is the breaking down of a stream in to its component parts, disregarding the syntax that stream contains. Parsing is actually including the syntax in order to make...
1
64197
AdrianH
by: AdrianH | last post by:
Assumptions I am assuming that you know or are capable of looking up the functions I am to describe here and have some remedial understanding of C programming. FYI Although I have called this article “How to Parse a File in C++”, we are actually mostly lexing a file which is the breaking down of a stream in to its component parts, disregarding the syntax that stream contains. Parsing is actually including the syntax in order to make...
0
9655
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10363
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10169
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10110
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
5398
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
5534
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4067
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
3670
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2894
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.