473,578 Members | 3,239 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

std::string question

Hello,

I would like to replace all the occurrence of "(" and ")"
in C++ std::string to "\(" and "\)".

For example:
string s = "(abc)|(toto)|( lala)"
will be become "\(abc\)|\(toto \)|\(lala\)"
Question:
Just wonder if there is a straight forward function to do so??
Currently I am using a while loop to read through the string, then
basic_string::f ind and basic_string::r eplace the occurrence of "(" and ")".

Any better solution?

Thanks,
Kian
Jul 22 '05 #1
6 2608

"Kian Goh" <ki**@hotmail.c om> wrote in message
news:g_******** ************@ro gers.com...
Hello,

I would like to replace all the occurrence of "(" and ")"
in C++ std::string to "\(" and "\)".

For example:
string s = "(abc)|(toto)|( lala)"
will be become "\(abc\)|\(toto \)|\(lala\)"
Question:
Just wonder if there is a straight forward function to do so??
No.


Currently I am using a while loop to read through the string, then
basic_string::f ind and basic_string::r eplace the occurrence of "(" and
")".

Any better solution?


Certainly there are bad ways and good ways to write this code but without
seeing the code you have written it is impossible to say whether there is a
better solution.

A good solution would work in three phases.

1) Go though the string seeing how many backslashes you are going to need to
insert
2) Increase the size of the string by the number of extra backslashes needed
3) Loop backwards though the string, copying characters and inserting
backslashes as necessary.

The point of this compexity is that it minimises reallocation of the string
and copying of characters.

A bad solution would work like this

1) Go forwards through the string and each time you find a "(" or ")" insert
a backslash.

john
Jul 22 '05 #2
"Kian Goh" <ki**@hotmail.c om> wrote in message
news:g_******** ************@ro gers.com...
Hello,

I would like to replace all the occurrence of "(" and ")"
in C++ std::string to "\(" and "\)".

For example:
string s = "(abc)|(toto)|( lala)"
will be become "\(abc\)|\(toto \)|\(lala\)"
Question:
Just wonder if there is a straight forward function to do so??
Currently I am using a while loop to read through the string, then
basic_string::f ind and basic_string::r eplace the occurrence of "(" and
")".

Any better solution?

Thanks,
Kian


Here is a solution:

string add_backslash_t o_brackets(char ch)
{
string s(1, ch);
if (ch == '(' || ch == ')')
s.insert(s.begi n(), '\\');
return s;
}

vector<string> v;
transform(s.beg in(), s.end(), back_inserter(v ), add_backslash_t o_brackets);
s = accumulate(v.be gin(), v.end(), string());

Hope you like it.
Jul 22 '05 #3
"Jason Heyes" <ja********@opt usnet.com.au> wrote in message
news:419b0f0b$0 $24380
"Kian Goh" <ki**@hotmail.c om> wrote in message
For example:
string s = "(abc)|(toto)|( lala)"
will be become "\(abc\)|\(toto \)|\(lala\)"

string add_backslash_t o_brackets(char ch)
{
string s(1, ch);
if (ch == '(' || ch == ')')
s.insert(s.begi n(), '\\');
return s;
}

vector<string> v;
transform(s.beg in(), s.end(), back_inserter(v ), add_backslash_t o_brackets); s = accumulate(v.be gin(), v.end(), string());


Good.

Along the same lines, the function back_inserter(v ) returns an iterator,
specifically a std::back_inser t_iterator<std: :vector<std::st ring>>, whose
operator= calls v.push_back(... ). You could write your own
back_insert_ite rator class too, thus avoiding the need to create strings and
a vector of strings.

class special_back_in sert_iterator : public
std::back_inser t_iterator<std: :string> {
typedef std::back_inser t_iterator<std: :string> inherited;
public:
special_back_in sert_iterator(s td::string& s) : inherited(s) { }
special_back_in sert_iterator& operator=(char c) {
if (ch == '(' || ch == ')') inherited::oper ator=('\\');
inherited::oper ator==(c);
return *this;
}
};

inline
special_back_in sert_iterator special_back_in serter(std::str ing&)
{
return ...;
}

string s2;
transform(s.beg in(), s.end(), special_back_in serter(s2));
Jul 22 '05 #4
"Siemel Naran" <Si*********@RE MOVE.att.net> wrote in message
news:nx******** ***********@bgt nsc05-news.ops.worldn et.att.net...
"Jason Heyes" <ja********@opt usnet.com.au> wrote in message
news:419b0f0b$0 $24380
"Kian Goh" <ki**@hotmail.c om> wrote in message

> For example:
> string s = "(abc)|(toto)|( lala)"
> will be become "\(abc\)|\(toto \)|\(lala\)"

string add_backslash_t o_brackets(char ch)
{
string s(1, ch);
if (ch == '(' || ch == ')')
s.insert(s.begi n(), '\\');
return s;
}

vector<string> v;
transform(s.beg in(), s.end(), back_inserter(v ),

add_backslash_t o_brackets);
s = accumulate(v.be gin(), v.end(), string());


Good.

Along the same lines, the function back_inserter(v ) returns an iterator,
specifically a std::back_inser t_iterator<std: :vector<std::st ring>>, whose
operator= calls v.push_back(... ). You could write your own
back_insert_ite rator class too, thus avoiding the need to create strings
and
a vector of strings.

class special_back_in sert_iterator : public
std::back_inser t_iterator<std: :string> {
typedef std::back_inser t_iterator<std: :string> inherited;
public:
special_back_in sert_iterator(s td::string& s) : inherited(s) { }
special_back_in sert_iterator& operator=(char c) {
if (ch == '(' || ch == ')') inherited::oper ator=('\\');
inherited::oper ator==(c);
return *this;
}
};

inline
special_back_in sert_iterator special_back_in serter(std::str ing&)
{
return ...;
}

string s2;
transform(s.beg in(), s.end(), special_back_in serter(s2));


Nice. It all happens in one line of STL. I wonder how these STL solutions
compare with non-STL ones in terms of code complexity. Alot better I
presume.
Jul 22 '05 #5
On Tue, 16 Nov 2004 21:59:27 -0500 in comp.lang.c++, "Kian Goh"
<ki**@hotmail.c om> wrote,
I would like to replace all the occurrence of "(" and ")"
in C++ std::string to "\(" and "\)".

#include <string>
#include <algorithm>
#include <numeric>
#include <iostream>

std::string changer(std::st ring was, char in)
{
if (in == '(')
return was+"\\(";
if (in == ')')
return was+"\\)";
return was+in;
};

int main()
{
std::string foo("(abc)|(tot o)|(lala)");
std::string bar = std::accumulate (foo.begin(), foo.end(),
std::string("") , changer);
std::cout << bar;
}

Jul 22 '05 #6
"Jason Heyes" <ja********@opt usnet.com.au> wrote in message
news:419b27d6$0 $27445
"Siemel Naran" <Si*********@RE MOVE.att.net> wrote in message

string s2;
transform(s.beg in(), s.end(), special_back_in serter(s2));


Nice. It all happens in one line of STL. I wonder how these STL solutions
compare with non-STL ones in terms of code complexity. Alot better I
presume.


Except for the meaningless name 'special_back_i nserter', the code above
looks simpler. However, it's not an inplace algorithm, therefore uses more
memory. John's suggestion is in in-place algorithm, though harder to
implement.
Jul 22 '05 #7

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

Similar topics

19
22718
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 the std::string a pointer and a length and then give the std::string control over the pointer and its content? I'm basically trying to avoid...
11
3630
by: Christopher Benson-Manica | last post by:
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 " ); }
19
6131
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 found anything). Here's the problem, I have two sets of files, the name of a file contains a number which is unique for each set but it's possible...
16
16403
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
13567
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!"; int size1 = sizeof(std::string); int size2 = sizeof(someString); and printed out the values of size1 and size2. size1 and size2 always
2
4801
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 std; int main()
1
1720
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 std; int main()
8
8310
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 object. My sample code is as follows. ..h file content---------- #include <stdio.h>
84
15824
by: Peter Olcott | last post by:
Is there anyway of doing this besides making my own string from scratch? union AnyType { std::string String; double Number; };
25
8326
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
7847
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...
0
7778
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8125
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. ...
0
6522
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5664
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...
0
5342
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...
0
3781
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...
1
2292
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
1
1389
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.