473,407 Members | 2,315 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,407 software developers and data experts.

strip commas from string


Hello all! I've been looking for a way to strip characters from strings
such as a comma. This would be great for using a comma
as a delimiter. I show you what I have right now.
#include<iostream>
#include<string>

int main(int argc, char *argv[])
{
using namespace std ;

char people[14] = "Me,Myself,I" ;
char nocommas[14] ;
int i, j ;
i=j=0 ;

for(i = 0; i < 14; i++){
if(people[i] != ',')
nocommas[i] = people[i] ;

if(people[i] == ',')
nocommas[i] = ' ' ;
}

cout << "With commas : " << people << endl ;
cout << "Without commas : " << nocommas << endl ;

cout << "\n\n\n\n" ;
cout << "\tNow tell me how I can store each name in a separate
variable ?" << endl ;
cout << "\tAnd can someone show me how to do this with string instead
of char[] ?" << endl ;
cout << "\t\t Thanks so much!" << endl ;

return 0 ;
}
so as you can see it strips commas and puts a space in its place.

Thanks for you help :-)

Jul 30 '05 #1
22 13714
in*************@yahoo.com wrote:
Hello all! I've been looking for a way to strip characters from strings
such as a comma. This would be great for using a comma
as a delimiter. I show you what I have right now.
Thank you for posting code. This really helps.


#include<iostream>
#include<string> You're not using std::string. So you _may_ not need
this header.


int main(int argc, char *argv[])
{
using namespace std ;

char people[14] = "Me,Myself,I" ;
char nocommas[14] ;
int i, j ;
i=j=0 ;

for(i = 0; i < 14; i++){
if(people[i] != ',')
nocommas[i] = people[i] ;

if(people[i] == ',')
nocommas[i] = ' ' ;
}

cout << "With commas : " << people << endl ;
cout << "Without commas : " << nocommas << endl ;

cout << "\n\n\n\n" ;
cout << "\tNow tell me how I can store each name in a separate
variable ?" << endl ;
cout << "\tAnd can someone show me how to do this with string instead
of char[] ?" << endl ;
cout << "\t\t Thanks so much!" << endl ;

return 0 ;
}
so as you can see it strips commas and puts a space in its place.

Thanks for you help :-)


1. See std::string class, especially the constructor:
std::string(char *)
So that you can use the find() member of the string class.

2. Also explore the strtok() and strchr() functions in the
"C" standard library.

--
Thomas Matthews

C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
http://www.comeaucomputing.com/learn/faq/
Other sites:
http://www.josuttis.com -- C++ STL Library book
http://www.sgi.com/tech/stl -- Standard Template Library

Jul 30 '05 #2
> Hello all! I've been looking for a way to strip characters from strings
such as a comma. This would be great for using a comma
as a delimiter. I show you what I have right now. cout << "\n\n\n\n" ;
cout << "\tNow tell me how I can store each name in a separate
variable ?" << endl ;
cout << "\tAnd can someone show me how to do this with string instead
of char[] ?" << endl ;
cout << "\t\t Thanks so much!" << endl ;

return 0 ;
}


to store "each name in a separate variable" you'll want a std::vector,
another container, or perhaps an array.

to split the string based upon commas, you can put the string in a
std::stringstream and then use std::getline:

std::istringstream ss("I,Myself,Me");
std::string name;
while(std::getline(ss, name, ',') {
/* push_back name onto the end of a std::vector or another container
*/
}

Jul 30 '05 #3
in*************@yahoo.com wrote:
Hello all! I've been looking for a way to strip characters from strings
such as a comma. This would be great for using a comma
as a delimiter. I show you what I have right now.
#include<iostream>
#include<string>

int main(int argc, char *argv[])
{
using namespace std ;

char people[14] = "Me,Myself,I" ;
char nocommas[14] ;
int i, j ;
i=j=0 ;

for(i = 0; i < 14; i++){
if(people[i] != ',')
nocommas[i] = people[i] ;

if(people[i] == ',')
nocommas[i] = ' ' ;
}

cout << "With commas : " << people << endl ;
cout << "Without commas : " << nocommas << endl ;

cout << "\n\n\n\n" ;
cout << "\tNow tell me how I can store each name in a separate
variable ?" << endl ;
cout << "\tAnd can someone show me how to do this with string instead
of char[] ?" << endl ;
cout << "\t\t Thanks so much!" << endl ;

return 0 ;
}
so as you can see it strips commas and puts a space in its place.

Thanks for you help :-)


Here's one possibility:
#include <iostream>
#include <sstream>
#include <string>
#include <list>

int main(int argc, char *argv[])
{
// the test string of comma-seperated words
char * people = "Me,Myself,I";

// make an input stream named 'in' from 'people'
std::istringstream in(people);

// 'words' will hold the list of words extracted from 'in'
std::list< std::string > words;

// while no error on 'in'
while(in)
{
// 'aWord' will hold the next word read from 'in'
std::string aWord;

// get all text from 'in' up to the next comma, or end of data,
// into 'aWord'
getline(in, aWord, ',');

// if no error on 'in', i.e. we read text into 'aWord',
// then put a copy of 'aWord' in to the 'words' list
if (in)
words.push_back(aWord);
}

std::cout << "Comma seperated words read from 'people' into the
'words' list"
<< std::endl;

// 'it' is an iterator for iterating over the content of the
// 'words' list
std::list< std::string >::iterator it;

// print all of the entries in 'words'
for (it = words.begin(); it != words.end(); it++)
std::cout << (*it) << std::endl;

return 0;
}

Regards,
Larry
Jul 30 '05 #4
in*************@yahoo.com wrote:
Hello all! I've been looking for a way to strip characters from strings
such as a comma. This would be great for using a comma
as a delimiter. I show you what I have right now.


I'm pretty new to C++ myself (I started learning two or three weeks
ago), so this is probably not the cleanest (or best) way to do this,
but it works - for me anyway (it compiles with g++ -Wall -ansi -pedantic
without any warnings, so it should probably work everwhere else, too).

I stayed pretty close to the code you already had, so you shouldn't have
any problems understanding it.
#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main(int argc, char **argv) {
string commas="Me,Myself,I";
if(argv[1]) commas=argv[1]; // Use commandline parameter as string
// if specified.
vector<string> nocommas(1);
int j=0;
for(unsigned int i=0; i<commas.length(); i++) {
if(commas[i]==',') { // If the current character is a comma,
nocommas.push_back(""); // add a new (empty) string to the vector
j++; // and increase the counter so that all
// future operations are performed on
the
// new string
}
else nocommas.at(j)+=commas[i]; // If it's not add the current char
// to the string with the number j
// in the vector
}
cout<<"With commas: "<<commas<<endl<<endl;
cout<<"From the array:"<<endl;
for(int i=0; i<=j; i++) {
cout<<"Word "<<i<<": "<<nocommas.at(i)<<endl;
}
return 0;
}

--
If geiger counter does not click,
the coffee, she is just not thick
Jul 30 '05 #5
Larry, why use std:: all the time? You can just put 'using namespace
std' at the beginning of your code :-)

Jul 30 '05 #6
in*************@yahoo.com wrote:
Larry, why use std:: all the time? You can just put 'using namespace
std' at the beginning of your code :-)


That can get you in trouble.
In a small program like this it's ok, but it can cause
unexpected problems in large apps where name conflicts
might occur with methods from other (3rd party) libs.

I explicitly use 'std::' in example programs so the reader
will be clear on where things come from in the example.

Regards,
Larry

Jul 30 '05 #7
Larry I Smith wrote:
in*************@yahoo.com wrote:
Larry, why use std:: all the time? You can just put 'using namespace
std' at the beginning of your code :-)


That can get you in trouble.
In a small program like this it's ok, but it can cause
unexpected problems in large apps where name conflicts
might occur with methods from other (3rd party) libs.

I explicitly use 'std::' in example programs so the reader
will be clear on where things come from in the example.

Regards,
Larry

For completeness, this line in my example:

getline(in, aWord, ',');

should be:

std::getline(in, aWord, ',');

In the absence of a "using namespace std;" declaration,
some compilers will compile the example ok, but some
will complain about not being able to find the appropriate
getline() function.

Regards,
Larry
Jul 30 '05 #8
>That can get you in trouble.
In a small program like this it's ok, but it can cause
unexpected problems in large apps where name conflicts
might occur with methods from other (3rd party) libs.


Ok Larry, I see now. You know I learn way more in the news groups
than I do from a text book ! By the way as far as text books go,
I'm studying from the Pearson Textbook series , C++ Today and C++
Primer.
They're good books but have me starting my progs with using namespace
and
sticking with char[] instead of string alot. And to sebastian, Alipha,
and Thomas ,
I appreciate your help too ! Larry, I never knew that putting 'Using
namespace whatever'
would get me into trouble until you demonstrated it to me in this
forum. From now
on I'm going to append std:: to all my std library functions and
objects.
I had to say all that to demonstrate my appreciation ... Thanks

Jul 30 '05 #9
in*************@yahoo.com wrote:
That can get you in trouble.
In a small program like this it's ok, but it can cause
unexpected problems in large apps where name conflicts
might occur with methods from other (3rd party) libs.


Ok Larry, I see now. You know I learn way more in the news groups
than I do from a text book ! By the way as far as text books go,
I'm studying from the Pearson Textbook series , C++ Today and C++
Primer.
They're good books but have me starting my progs with using namespace
and
sticking with char[] instead of string alot. And to sebastian, Alipha,
and Thomas ,
I appreciate your help too ! Larry, I never knew that putting 'Using
namespace whatever'
would get me into trouble until you demonstrated it to me in this
forum. From now
on I'm going to append std:: to all my std library functions and
objects.
I had to say all that to demonstrate my appreciation ... Thanks


The use of 'using namespace std;' versus explicit 'std::' is a decision
that needs to be made on a project-by-project basis. If you are not
linking with multiple libs and the project is small, then the 'using'
declaration is fine. If the project is large and you are linking
with multiple libs then explicit use of 'std::' might be a better
option. Most IT departments have some kind of guidelines for their
developers spelling out the corporation's C++ standards. It just
happens that my employer expects the use of 'std::' in all but the
most trivial programs.

Like anything else, do what makes sense for the particular project.

Regards,
Larry
Jul 30 '05 #10
What do you mean by linking with multiple libs ? You mean like if I
want to use
ncurses in a Linux program I would link more than one lib by doing :

mycomp$> gcc -o ncursesprog ncursesprog.cpp -lncurses

By putting the -lncurses I would be linking with more than one lib then
?

Jul 30 '05 #11
in*************@yahoo.com wrote:
What do you mean by linking with multiple libs ? You mean like if I
want to use
ncurses in a Linux program I would link more than one lib by doing :

mycomp$> gcc -o ncursesprog ncursesprog.cpp -lncurses

By putting the -lncurses I would be linking with more than one lib then
?


In general, yes -lncurses causes an additional lib to be linked
in addition to the Std libs that are linked by default.

Always use 'g++' rather than 'gcc' to compile and link C++
programs. g++ passes additional info to the linker specific
to C++ programs (like the list of Std libs to link, etc). e.g.

g++ -o ncursesprog ncursesprog.cpp -lncurses

Use 'gcc' for 'C' programs and 'g++' for C++ and mixed
'C' & C++ programs.

The newsgroup for GCC 'gcc' is: gnu.gcc.help
The newsgroup for GCC 'g++' is: gnu.g++.help

Regards,
Larry
Jul 30 '05 #12
Larry I Smith wrote:
The use of 'using namespace std;' versus explicit 'std::' is a decision
that needs to be made on a project-by-project basis. If you are not


What do you mean? Do you think is reasonable in any project to force to use
a "using namespace std" in all translation units? Or to put in in header
files? If it is that, I don't think that nobody will agree with that.

Unless the project is sooooo small that nobody cares about his maintenance,
of course.

--
Salu2
Jul 30 '05 #13
Julián Albo wrote:
Larry I Smith wrote:
The use of 'using namespace std;' versus explicit 'std::' is a decision
that needs to be made on a project-by-project basis. If you are not


What do you mean? Do you think is reasonable in any project to force to use
a "using namespace std" in all translation units? Or to put in in header
files? If it is that, I don't think that nobody will agree with that.

Unless the project is sooooo small that nobody cares about his maintenance,
of course.


No, In fact, we never use 'using namespace std;', but in a very small
program, like the example code in this thread, it's ok.

Regards,
Larry
Jul 30 '05 #14
So what would be the std libs I can link with ? I mean is there a such
thing as iostream.lib ? I did a harddrive search and nothing like that
was found. I would like to know. By the way Larry, I type in the
example
program you added to this thread which separated words and used
the header files sstream and list. Here's the output I got

Comma separated words read from 'people' into the 'words' list
me
myself
i

I like the way they list one underneath the other like that . In any
case I'm
going to need practice using headers list and sstream. So much to
learn!

Sincerelly,

Me

Jul 30 '05 #15
in*************@yahoo.com wrote:
So what would be the std libs I can link with ? I mean is there a such
thing as iostream.lib ? I did a harddrive search and nothing like that
was found. I would like to know.
[snip]
Me


The Std lib names vary from platform to platform.
Consult your compiler and Operating System documentation
for details.

For example, on my Linux system, the C++ Std lib is:

libstdc++.so.5.0.

and is passed to the linker by 'g++' as '-lstdc++'

It'll be different on Windows, Solaris, HP-UX, AIX, etc.
Different libs may be linked based on compiler flags:

compile multi-threaded yes/no
compile debug yes/no
use Network sockets yes/no
etc, etc, etc

Ask additional question in the newsgroup(s) associated
with your compiler and Operating System.

Regards,
Larry
Jul 30 '05 #16

<in*************@yahoo.com> skrev i en meddelelse
news:11**********************@g43g2000cwa.googlegr oups.com...

Hello all! I've been looking for a way to strip characters from strings
such as a comma. This would be great for using a comma
as a delimiter. I show you what I have right now.


[snip]

so as you can see it strips commas and puts a space in its place.

Thanks for you help :-)

If you want to replace commas with spaces simply do:
std::string s;

s.replace(s.begin(),s.end(),',',' ');

if you want ro remove commas use:

std::string s;

s.erase(std::remove(s.begin(),s.end(),','),s.end() );

You can use similar code for char* strings.

/Peter
Jul 31 '05 #17
Wow that really makes it easy :-) Thanks Peter!

Jul 31 '05 #18
Ram
Yes, using std::string functions is the most recommended & convenient
way. You might find it useful to explore other std::string functions,
there's one for almost every common task associated with a string.

Ramashish

Jul 31 '05 #19
Hello there,

The following snippet may be useful;
char s[10];
...
...
for (i=0,s[i]=strtok(input,",");s[i]!=NULL;s[i]=strtok(NULL,","),i++)
printf("String i --> %s \n",s[i]);
...
...

/Rajesh

in*************@yahoo.com wrote:
Hello all! I've been looking for a way to strip characters from strings
such as a comma. This would be great for using a comma
as a delimiter. I show you what I have right now.
#include<iostream>
#include<string>

int main(int argc, char *argv[])
{
using namespace std ;

char people[14] = "Me,Myself,I" ;
char nocommas[14] ;
int i, j ;
i=j=0 ;

for(i = 0; i < 14; i++){
if(people[i] != ',')
nocommas[i] = people[i] ;

if(people[i] == ',')
nocommas[i] = ' ' ;
}

cout << "With commas : " << people << endl ;
cout << "Without commas : " << nocommas << endl ;

cout << "\n\n\n\n" ;
cout << "\tNow tell me how I can store each name in a separate
variable ?" << endl ;
cout << "\tAnd can someone show me how to do this with string instead
of char[] ?" << endl ;
cout << "\t\t Thanks so much!" << endl ;

return 0 ;
}
so as you can see it strips commas and puts a space in its place.

Thanks for you help :-)


Aug 1 '05 #20
SUNROCKET FREE PHONES HERE
SunRocket Promotion Free Phones!
http://sunrocket.blogspot.com
[b:adb10dde8a][color=red:adb10dde8a]SUNROCKET BLOG
Recieve two FREE Uniden Cordless
phones[/color:adb10dde8a][/b:adb10dde8a]

http://img461.imageshack.us/img461/4...ketnew25ub.jpg
Sent via Archivaty.com
Nov 22 '05 #21
SUNROCKET FREE PHONES HERE
SunRocket Promotion Free Phones!
http://sunrocket.blogspot.com
[b:0a2b1f0e20][color=red:0a2b1f0e20]SUNROCKET BLOG
Recieve two FREE Uniden Cordless
phones[/color:0a2b1f0e20][/b:0a2b1f0e20]

http://img461.imageshack.us/img461/4...ketnew25ub.jpg
Sent via Archivaty.com
Nov 22 '05 #22

"SUNROCKET" <RE*******@MAILINATOR-dot-COM.no-spam.invalid> wrote in
message news:1N******************************@giganews.com ...

<snip>

for the record: ab***@giganews.com
and a full header + message was sent.

We don't need total idiots here. Specially an idiot that configures the
newsreader to only show unread messages. If you composed it, you've read
it, duh!
Nov 22 '05 #23

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

Similar topics

5
by: qwweeeit | last post by:
Hi all, I need to limit as much as possible the lenght of a source line, stripping white spaces (except indentation). For example: .. . max_move and AC_RowStack.acceptsCards ( self,...
6
by: Markus Rosenstihl | last post by:
Hi, I wonder if i can make this nicer: In my case a list is created from a bill which is a tab seperated file and each line looks like this: "Verbindungen Deutsche Telekom vom 03.08.2005 bis...
6
by: Mark Miller | last post by:
I have a scheduled job that uses different XSL templates to transform XML and save it to disk. I am having problems with the code below. The problem shows up on both my development machine (Windows...
6
by: dixie | last post by:
I have a text field on a form which has names with a comma between them like this: 'J. Smith, A. Jones, A. Man, J. Johns'. I am trying to find a procedure that will count the number of people in...
5
by: dan.j.weber | last post by:
I'm using Python 2.3.5 and when I type the following in the interactive prompt I see that strip() is not working as advertised: >>>s = 'p p:p' >>>s.strip(' :') 'p p:p' Is this just me or...
0
by: Brian Henry | last post by:
I thought this was useful, its a extender i just wrote for the new .NET menu strip and status strip to extend the menu items to add a status message so when a mouse rolls over the item it displays...
6
by: rtilley | last post by:
s = ' qazwsx ' # How are these different? print s.strip() print str.strip(s) Do string objects all have the attribute strip()? If so, why is str.strip() needed? Really, I'm just curious......
6
by: eight02645999 | last post by:
hi can someone explain strip() for these : 'example' when i did this: 'abcd,words.words'
3
by: Colin J. Williams | last post by:
The Library Reference has strip( ) Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed....
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
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,...
0
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...
0
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...

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.