473,398 Members | 2,404 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,398 software developers and data experts.

Quick std::string question

Let's say I have a std::string, and I want to replace all the ','
characters with " or ", i.e. "A,B,C" -> "A or B or C". Is the
following the best way to do it?

int idx;
while( (idx=str.find_first_of(',')) >= 0 ) {
str.replace( idx, 1, "" );
str.insert( idx, " or " );
}

(Stroustrup wasn't too illuminating here, unfortunately.)

--
Christopher Benson-Manica | I *should* know what I'm talking about - if I
ataru(at)cyberspace.org | don't, I need to know. Flames welcome.
Jul 22 '05 #1
11 3612
On Mon, 9 Feb 2004 21:18:47 +0000 (UTC), Christopher Benson-Manica
<at***@nospam.cyberspace.org> wrote:
Let's say I have a std::string, and I want to replace all the ','
characters with " or ", i.e. "A,B,C" -> "A or B or C". Is the
following the best way to do it?

int idx;
while( (idx=str.find_first_of(',')) >= 0 ) {
str.replace( idx, 1, "" );
str.insert( idx, " or " );
}

(Stroustrup wasn't too illuminating here, unfortunately.)


See if this will work for you:

///
/// Replace all occurences of a substring in a string with another
/// string, in-place.
///
/// @param s String to replace in. Will be modified.
/// @param sub Substring to replace.
/// @param other String to replace substring with.
///
/// @return The string after replacements.
inline std::string &
replacein(std::string &s, const std::string &sub,
const std::string &other)
{
assert(!sub.empty());
size_t b = 0;
for (;;)
{
b = s.find(sub, b);
if (b == s.npos) break;
s.replace(b, sub.size(), other);
b += other.size();
}
return s;
}

--
Be seeing you.
Jul 22 '05 #2
Christopher Benson-Manica wrote:
Let's say I have a std::string, and I want to replace all the ','
characters with " or ", i.e. "A,B,C" -> "A or B or C". Is the
following the best way to do it?

int idx;
while( (idx=str.find_first_of(',')) >= 0 ) {
This will start from the beginning for each ',' that was found and again
search the already searched parts. I'd replace the above two lines
with:

int idx = 0;
while( (idx=str.find_first_of(',', idx)) >= 0 ) {

You could even save a bit more by jumping over the replacement text,
too.
str.replace( idx, 1, "" );
str.insert( idx, " or " );

Why do you first replace the ',' with an empty string and then insert
the " or " instead of just replacing it directly with " or "?

str.replace(idx, 1, " or ");
}

(Stroustrup wasn't too illuminating here, unfortunately.)


--
Never wondered why a carrot is more orange than an orange?

Jul 22 '05 #3
"Christopher Benson-Manica" <at***@nospam.cyberspace.org> wrote in message
news:c0**********@chessie.cirr.com...
Let's say I have a std::string, and I want to replace all the ','
characters with " or ", i.e. "A,B,C" -> "A or B or C". Is the
following the best way to do it?

int idx;
while( (idx=str.find_first_of(',')) >= 0 ) {
str.replace( idx, 1, "" );
str.insert( idx, " or " );
}

(Stroustrup wasn't too illuminating here, unfortunately.)


For more versatility, I've changed your 'character to find'
to 'string to find':
#include <iostream>
#include <string>

/* If 'from' matches 'to' or 'from' is empty, */
/* does not parse 's', returns std::string::npos */
/* */
/* Otherwise returns number of replacements done */
/* */

std::string::size_type repl(std::string& s,
const std::string& from,
const std::string& to)
{
std::string::size_type cnt(std::string::npos);

if(from != to && !from.empty())
{
std::string::size_type pos1(0);
std::string::size_type pos2(0);
const std::string::size_type from_len(from.size());
const std::string::size_type to_len(to.size());
cnt = 0;

while((pos1 = s.find(from, pos2)) != std::string::npos)
{
s.replace(pos1, from_len, to);
pos2 = pos1 + to_len;
++cnt;
}
}

return cnt;
}

int main()
{
std::string s("A,B,C");

const std::string old_seq(",");
const std::string new_seq(" or ");

std::cout << "Original string:\n"
<< '"' << s << '"'
<< "\n\n";

const std::string::size_type count(repl(s, old_seq, new_seq));
const std::string dq(count > 0, '"');
const bool parsed(count != std::string::npos);
const bool found(parsed && count > 0);

if(parsed)
{
std::cout << count
<< " occurences of sequence \"" << old_seq << "\""
<< (count ? " replaced with sequence " : " found")
<< dq << (count ? new_seq : "") << dq
<< "\n\n";
}
else
std::cout << "Nothing to change\n\n";

std::cout << (parsed && found
? std::string("New string:\n" + dq + s + dq)
: "No changes made")
<< '\n';

return 0;
}

Original string:
"A,B,C"

2 occurences of sequence "," replaced with sequence " or "

New string:
"A or B or C"

HTH,
-Mike

Jul 22 '05 #4
"Christopher Benson-Manica" <at***@nospam.cyberspace.org> wrote in message
news:c0**********@chessie.cirr.com...
Let's say I have a std::string, and I want to replace all the ','
characters with " or ", i.e. "A,B,C" -> "A or B or C". Is the
following the best way to do it?

int idx;
while( (idx=str.find_first_of(',')) >= 0 ) {
str.replace( idx, 1, "" );
str.insert( idx, " or " );
}

(Stroustrup wasn't too illuminating here, unfortunately.)

--
Christopher Benson-Manica | I *should* know what I'm talking about - if I
ataru(at)cyberspace.org | don't, I need to know. Flames welcome.


std::string // replace all instances of victim with replacement
mass_replace(const std::string &source, const std::string &victim, const
std::string &replacement)
{
std::string answer = source;
std::string::size_type j = 0;
while ((j = answer.find(victim, j)) != std::string::npos )
answer.replace(j, victim.length(), replacement);
return answer;
}

--
Cy
http://home.rochester.rr.com/cyhome/
Jul 22 '05 #5
On Tue, 10 Feb 2004 00:21:02 GMT, "Cy Edmunds"
<ce******@spamless.rochester.rr.com> wrote:
Let's say I have a std::string, and I want to replace all the ','
characters with " or ", i.e. "A,B,C" -> "A or B or C". Is the
following the best way to do it?

int idx;
while( (idx=str.find_first_of(',')) >= 0 ) {
str.replace( idx, 1, "" );
str.insert( idx, " or " );
}

(Stroustrup wasn't too illuminating here, unfortunately.)
std::string // replace all instances of victim with replacement
mass_replace(const std::string &source, const std::string &victim, const
std::string &replacement)
{
std::string answer = source;
std::string::size_type j = 0;
while ((j = answer.find(victim, j)) != std::string::npos )
answer.replace(j, victim.length(), replacement);
return answer;
}


This function doesn't work.

mass_replace("a", "a", "a");

Oops.

--
Be seeing you.
Jul 22 '05 #6
"Thore Karlsen" <si*@6581.com> wrote in message
news:qk********************************@4ax.com...
On Tue, 10 Feb 2004 00:21:02 GMT, "Cy Edmunds"
std::string // replace all instances of victim with replacement
mass_replace(const std::string &source, const std::string &victim, const
std::string &replacement)
{
std::string answer = source;
std::string::size_type j = 0;
while ((j = answer.find(victim, j)) != std::string::npos )
answer.replace(j, victim.length(), replacement);
return answer;
}


This function doesn't work.

mass_replace("a", "a", "a");

Oops.


Try mine, I spent a bit of time testing it for such corner cases
(since I needed to write something like that for myself anyway).

Of course I might have missed something... :-)

-Mike
Jul 22 '05 #7
On Tue, 10 Feb 2004 01:35:06 GMT, "Mike Wahler" <mk******@mkwahler.net>
wrote:
>std::string // replace all instances of victim with replacement
>mass_replace(const std::string &source, const std::string &victim, const
>std::string &replacement)
>{
> std::string answer = source;
> std::string::size_type j = 0;
> while ((j = answer.find(victim, j)) != std::string::npos )
> answer.replace(j, victim.length(), replacement);
> return answer;
>}
This function doesn't work.

mass_replace("a", "a", "a");

Oops.
Try mine, I spent a bit of time testing it for such corner cases
(since I needed to write something like that for myself anyway).


Thanks, but I already have my own, which I posted. :)

--
Be seeing you.
Jul 22 '05 #8

"Thore Karlsen" <si*@6581.com> wrote in message
news:di********************************@4ax.com...
On Tue, 10 Feb 2004 01:35:06 GMT, "Mike Wahler" <mk******@mkwahler.net>
wrote:
>std::string // replace all instances of victim with replacement
>mass_replace(const std::string &source, const std::string &victim, const >std::string &replacement)
>{
> std::string answer = source;
> std::string::size_type j = 0;
> while ((j = answer.find(victim, j)) != std::string::npos )
> answer.replace(j, victim.length(), replacement);
> return answer;
>} This function doesn't work.

mass_replace("a", "a", "a");

Oops.

Try mine, I spent a bit of time testing it for such corner cases
(since I needed to write something like that for myself anyway).


Thanks, but I already have my own, which I posted. :)


Sorry, I got the thread mixed up. I though I was replying to OP.

-Mike
Jul 22 '05 #9
Hi Mike.

"Mike Wahler" <mk******@mkwahler.net> wrote in message
news:ez*******************@newsread1.news.pas.eart hlink.net...
| "Thore Karlsen" <si*@6581.com> wrote in message
| news:qk********************************@4ax.com...
| > On Tue, 10 Feb 2004 00:21:02 GMT, "Cy Edmunds"
| >
| > >std::string // replace all instances of victim with replacement
| > >mass_replace(const std::string &source, const std::string &victim, const
| > >std::string &replacement)
| > >{
| > > std::string answer = source;
| > > std::string::size_type j = 0;
| > > while ((j = answer.find(victim, j)) != std::string::npos )
| > > answer.replace(j, victim.length(), replacement);
| > > return answer;
| > >}
| >
| > This function doesn't work.
| >
| > mass_replace("a", "a", "a");
| >
| > Oops.
|
| Try mine, I spent a bit of time testing it for such corner cases
| (since I needed to write something like that for myself anyway).
|
| Of course I might have missed something... :-)

Since you're interested in such an exercise for yourself,
then I thought the following might interest you too ;-):

# include <iostream>
# include <ostream>
# include <string>

inline std::string TrimBS( const std::string& S,
const std::string& Junk = " \a\b\f\t\n\r\v," )
{
const std::string::size_type First( S.find_first_not_of( Junk ) );
const std::string::size_type Last( S.find_last_not_of( Junk ) );

return ( First == std::string::npos ) ?
std::string( "" ) : S.substr( First, Last - First + 1 );
}

inline void ReplaceTokens( std::string& S, const std::string& Token )
{
S = TrimBS( S );
std::string::size_type Idx( 0 );
std::string::size_type Pos( 0 );
std::string::size_type Start( 0 );

static const char* GoodChars( "abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" );

while( ( Pos = S.find_first_not_of( GoodChars, Start ) ) != std::string::npos )
{
if( ( Idx = S.find_first_of( GoodChars, Pos ) ) != std::string::npos )
{
S.erase( Pos, Idx - Pos );
S.insert( Pos, Token );
}

Start = Pos + Token.size();
}
}

int main()
{
std::string S( " A , B, C , D,Z, " );

std::cout << S << std::endl;
ReplaceTokens( S, " or " );
std::cout << S << std::endl;

return 0;
}

-- Input --
A , B, C , D,Z,

-- Output --
A or B or C or D or Z

Cheers.
Chris Val
Jul 22 '05 #10
Rolf Magnus <ra******@t-online.de> spoke thus:
Why do you first replace the ',' with an empty string and then insert
the " or " instead of just replacing it directly with " or "? str.replace(idx, 1, " or ");


Probably because I'm dumb (and Stroustrup doesn't go into specifics on
the std::string functions). Thanks.

--
Christopher Benson-Manica | I *should* know what I'm talking about - if I
ataru(at)cyberspace.org | don't, I need to know. Flames welcome.
Jul 22 '05 #11

"Chris ( Val )" <ch******@bigpond.com.au> wrote in message
news:c0*************@ID-110726.news.uni-berlin.de...
Hi Mike.

Since you're interested in such an exercise for yourself,
then I thought the following might interest you too ;-):


[snip misc string handling functions]

Thanks, Chris.

-Mike
Jul 22 '05 #12

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

Similar topics

19
by: Espen Ruud Schultz | last post by:
Lets say I have a char pointer and an std::string. Is it possible to get a pointer to the std::string's "content" so that the char pointer can point to the same text? And vice versa; can I give...
19
by: Erik Wikström | last post by:
First of all, forgive me if this is the wrong place to ask this question, if it's a stupid question (it's my second week with C++), or if this is answered some place else (I've searched but not...
16
by: Khuong Dinh Pham | last post by:
I have the contents of an image of type std::string. How can I make a CxImage object with this type. The parameters to CxImage is: CxImage(byte* data, DWORD size) Thx in advance
12
by: jl_post | last post by:
Dear C++ community, I have a question regarding the size of C++ std::strings. Basically, I compiled the following code under two different compilers: std::string someString = "Hello, world!";...
2
by: zhege | last post by:
I am a beginner of C++; I have a question about the std:string and std:cout class; Two pieces of code: -------------------------------- #include <iostream> #include <string> using namespace...
1
by: zhege | last post by:
I am a beginner of C++; I have a question about the std:string and std:cout class; Two pieces of code: -------------------------------- #include <iostream> #include <string> using namespace...
8
by: vidya.bhagwath | last post by:
Hello Experts, I am using std::string object as a member variable in one of the my class. The same class member function operates on the std::string object and it appends some string to that...
2
by: HerbD | last post by:
I have a loooong debugging session behind me! I finally found the reason for the problem and now would like to know, if it is a bug in my code or not standardconformant behavour of the compiler(s) or...
25
by: Bala2508 | last post by:
Hi, I have a C++ application that extensively uses std::string and std::ostringstream in somewhat similar manner as below std::string msgHeader; msgHeader = "<"; msgHeader += a; msgHeader...
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: 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
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
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
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
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...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
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.