Solved

std::string replace function

Posted on 2002-04-18
17
14,386 Views
Last Modified: 2011-08-18
I'm having issues find any example code on using std::replace.   I have
looked and what I'm finding doesn't make a lot of since.

std::string szMyString = "";
..
..
szMyString.append("EXEC sp_MyProc ");

Here I have a SQL statement that was passed in and I'm just wanting to save
the SQL statement off to an Audit table so we can't find when and what was
executed..

The SQL statement being passed to me is ExecMsg[255].   What I'm needing to
do is take this var, put it in the szMyString, then replace all the single
quotes with two single quotes, so SQL don't freak out on me when I go to
insert it.

szMyString.append(ExecMsg);

Now how do I replace all the single quotes with two single quotes?

These don't seem to work..   Looking around I don't understand exacly what
is needing passed in.

szMyString.replace(1, szMyString.length(), "'", "''");
szMyString.replace(1, "'", "''");

Thanx for your time..
0
Comment
Question by:Chizl
  • 7
  • 7
  • 2
  • +1
17 Comments
 
LVL 30

Expert Comment

by:Axter
ID: 6950936
Here's an example code using the std::replace function:

#include <algorithm>

int main(int, char*)
{
     char data[] = "television+video+telephone+cassette recorder+";
     std::replace(data,data+strlen(data), '+','\n');
     printf("%s\n", data);

     system("pause");
     return 0;
}

0
 
LVL 4

Author Comment

by:Chizl
ID: 6950960
I'd rather use std::string's replace function, but I tried your way.

I added:
#include <algorithm>

I tried:
std::replace(ExecMsg,ExecMsg+strlen(ExecMsg), "'","''");

I'm getting:
:\code\C++\CDE v2\CDE\CDE.cpp(99) : error C2782: 'void __cdecl std::replace(_FI,_FI,const _Ty &,const _Ty &)' : template parameter '_Ty' is ambiguous
        could be 'char [3]'
        or       'char [2]'
0
 
LVL 86

Expert Comment

by:jkr
ID: 6950969
'string::replace()' actually doesn't do what what you expect it to do - use

string single_quote = "\"";
string two_single_quotes = "\"\"";
int i = 0;
while ( string::npos != ( i = szMyString.find_first_of ( single_quote, i)) {

 szMyString.replace ( i, i + 1, two_single_quotes);

 i += 2;
}
0
 
LVL 5

Expert Comment

by:proskig
ID: 6950970
Chizl,
note that although Axter's example is completely valid, it needs to be modified for your case. The thing is that Axter uses std::replace, which has signature similar to following:

void replace (ForwardIterator beg, ForwardIterator end, const T& oldValue, const T& newValue);

In case of a string it can replace single character for another single character. There is no way to replace one character for two!
What you can do is to use replace which is a member of basic_string. Simple example would be

szMyString.replace(szMyString.find("'"), 1, "''");

But it will replace only first occurance, what you need is to write a loop, which repeasts this operation.
0
 
LVL 5

Expert Comment

by:proskig
ID: 6950974
sorry, I saw only first post, when started my own post
0
 
LVL 4

Author Comment

by:Chizl
ID: 6951102
jkr,
   That seems like a work around to what I'm wanting.

proskiq,
   That is what I'm looking for, but small problem.  hehe
   
   Lets say szMyString has "abcd'abcd'abcd'" in it.

   Run this:
   szMyString.replace(szMyString.find("'"), 1, "''");

   Return is:
   "abcd''abcd'abcd'"

Closer than I have been..  Need more than just the first one changed, I need all them changed.

I went through and tried changing things around, like changing the 1 to a 2 to see what happens.. Nothing..  I tried puting in the 4th parm szMyString.length(), but that ended up cutting my string in half..  
0
 
LVL 30

Expert Comment

by:Axter
ID: 6951124
You really should be using the std::replace function for this.
You're only replacing a single charactor with another single charactor, so the std::replace function is optimize for this type of algorithm
0
 
LVL 30

Expert Comment

by:Axter
ID: 6951141
Second example:

int main(int, char*)
{
     string szMyString = "television'video'telephone'cassette recorder'";
     std::replace(szMyString.begin(),szMyString.end(), '\'','\"');
     cout << szMyString << endl;

     system("pause");
     return 0;
}
0
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 
LVL 4

Author Comment

by:Chizl
ID: 6951217
jkr,
  I see what your doing and if that is what replace needs to be used I understand now.   I tried that way, but it deletes most of the string, not just the single quote, and replace it with the double quote.

I'm doing different things with your code to see if I can fix the issue..
0
 
LVL 30

Expert Comment

by:Axter
ID: 6951220
proskig,
>>note that although Axter's example is completely valid,
>>it needs to be modified for your case. The thing
>>is that Axter uses std::replace, which has signature
>>similar to following:

The questioner is only replacing a single charactor, so the method I posted is the correct one.


*****************************************************
He/She is talking about a single quote charactor (') VS a double quote charactor (")
*****************************************************

Chizl,
>>I'd rather use std::string's replace function, but I
>>tried your way.

If you use std::string's replace method, it will take more code, and it will be less optimize.
So it's a loose loose method.  You gain nothing, and loose optimisation and code simplicity.
0
 
LVL 4

Author Comment

by:Chizl
ID: 6951229
Axter,
   If you can tell me why I get compile errors, I would be happy to use..

C:\code\C++\CDE v2\CDE\CDE.cpp(100) : error C2782: 'void __cdecl std::replace(_FI,_FI,const _Ty &,const _Ty &)' : template parameter '_Ty' is ambiguous
        could be 'int'
        or       'char'
Error executing cl.exe.
0
 
LVL 30

Accepted Solution

by:
Axter earned 200 total points
ID: 6951232
Chizl,

Did you try it the way I posted it in the last example?

std::replace(szMyString.begin(),szMyString.end(), '\'','\"');

Use Single Quotes instead of double quotes.
0
 
LVL 4

Author Comment

by:Chizl
ID: 6951238
This is a basic non-mfc console display c++ application.
0
 
LVL 30

Expert Comment

by:Axter
ID: 6951239
>>If you can tell me why I get compile errors, I would be
>>happy to use..

You're getting a compiler error because you used double quotes around the charactors.
Use single quotes as posted in my last example;
Copy and paste for best results.
0
 
LVL 4

Author Comment

by:Chizl
ID: 6951247
Yes, but I found the problem..

I need to replace 1 single quote with two single quotes.  Your example has 1 single quote and replaces it with 1 double quote.

When I changed your code to this is when I get the error..
std::replace(szExecMsg.begin(),szExecMsg.end(), '\'','\'\'');
0
 
LVL 30

Expert Comment

by:Axter
ID: 6951288
Chizl,
>>I need to replace 1 single quote with two single quotes.
Sorry.  Disregard ALL my comments.  I misinterpret your requirements.

My method will not work.

I think jkr's method is more of what you need.
0
 
LVL 4

Author Comment

by:Chizl
ID: 6951312
I went ahead and went with the " instead of the '', so I can just past this..  

Thanx.
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Often, when implementing a feature, you won't know how certain events should be handled at the point where they occur and you'd rather defer to the user of your function or class. For example, a XML parser will extract a tag from the source code, wh…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now