473,581 Members | 2,607 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

search and replace

C++ers:

Here's an open ended STL question. What's the smarmiest most templated way
to use <string>, <algorithms> etc. to turn this:

" able search baker search charlie "

into this:

" able replace baker replace charlie "

Note that "replace" has one more letter than "search", so you can't do an
inplace substitution.

An alternate prize goes to whoever provides an efficient way (that doesn't
use simple things like character pointers and buffers and C things ;).

(We are aware several C++ Regexps are available; we just need to learn more
raw STL here.)

--
Phlip
http://www.greencheese.org/ZeekLand <-- NOT a blog!!!
Nov 10 '05 #1
22 11095
Tom


"Phlip" <ph******@yahoo .com> wrote in message
news:hn******** ********@newssv r17.news.prodig y.com...
C++ers:

Here's an open ended STL question. What's the smarmiest most templated way
to use <string>, <algorithms> etc. to turn this:

" able search baker search charlie "

into this:

" able replace baker replace charlie "

Note that "replace" has one more letter than "search", so you can't do an
inplace substitution.
The maximum number of chars in the resultant string in the
worst-case-scenario is

newLen = (oldLen/sizeOf(SearchSt ring) )*sizeOf(Replac eString);

so create a memory buffer with the above lenght, and keep inserting strings
from the source to this buffer, word by word, until you hit the searchword.
when you hit the searchword,
instead of inserting the searchword, insert the replace word.

hope you followd that, if you need code.. mail back to the group.


An alternate prize goes to whoever provides an efficient way (that doesn't
use simple things like character pointers and buffers and C things ;).

(We are aware several C++ Regexps are available; we just need to learn
more raw STL here.)

--
Phlip
http://www.greencheese.org/ZeekLand <-- NOT a blog!!!

Nov 10 '05 #2

These days every post here smells way too much like homework, but I'll
give you the benefit of the doubt :D.

Phlip wrote:
Here's an open ended STL question. What's the smarmiest most templated way
to use <string>, <algorithms> etc. to turn this:

" able search baker search charlie "

into this:

" able replace baker replace charlie "
I'm not really sure why you would need either <algorithm> or templates
here. Unless you want to be able to replace an int inside a string or
similar. Hmmmm...
Note that "replace" has one more letter than "search", so you can't do an
inplace substitution.


Why not? Watch me :D

#include <string>
#include <iostream>

using namespace std;

int main()
{
const string search = "search";
const string replace = "replace";

string text = " able search baker search charlie ";

string::size_ty pe found_at = text.find( search );
while( string::npos != found_at )
{
text.replace( found_at, search.length() , replace );
found_at = text.find( search, found_at + search.length() );
}

cout << text << endl;
}

Cheers,
Andre

Nov 10 '05 #3
Phlip wrote:
C++ers:

Here's an open ended STL question. What's the smarmiest most templated way
to use <string>, <algorithms> etc. to turn this:

" able search baker search charlie "

into this:

" able replace baker replace charlie "

Note that "replace" has one more letter than "search", so you can't do an
inplace substitution.


Ok, it's not templated; but it is short:

#include <iostream>
#include <string>

void replace_all ( std::string & str,
std::string const & pattern,
std::string const & replacement ) {
std::string::si ze_type start = str.find( pattern, 0 );
while ( start != str.npos ) {
str.replace( start, pattern.size(), replacement );
start = str.find( pattern, start+replaceme nt.size() );
}
}

int main ( void ) {
std::string banner = " able search baker search charlie ";
std::string pattern = "search";
std::string replacement = "replace";
std::cout << banner << '\n';
replace_all ( banner, pattern, replacement );
std::cout << banner << '\n';
}
Best regards

Kai-Uwe Bux

Nov 10 '05 #4
in*****@gmail.c om wrote:

These days every post here smells way too much like homework, but I'll
give you the benefit of the doubt :D.

Phlip wrote:
Here's an open ended STL question. What's the smarmiest most templated
way to use <string>, <algorithms> etc. to turn this:

" able search baker search charlie "

into this:

" able replace baker replace charlie "


I'm not really sure why you would need either <algorithm> or templates
here. Unless you want to be able to replace an int inside a string or
similar. Hmmmm...
Note that "replace" has one more letter than "search", so you can't do an
inplace substitution.


Why not? Watch me :D

#include <string>
#include <iostream>

using namespace std;

int main()
{
const string search = "search";
const string replace = "replace";

string text = " able search baker search charlie ";

string::size_ty pe found_at = text.find( search );
while( string::npos != found_at )
{
text.replace( found_at, search.length() , replace );
found_at = text.find( search, found_at + search.length() );
}

cout << text << endl;
}


Why not? here is why:

#include <string>
#include <iostream>

using namespace std;

int main()
{
const string search = "search";
const string replace = "devious_search _replacement";

string text = " able search baker search charlie ";

string::size_ty pe found_at = text.find( search );
while( string::npos != found_at )
{
text.replace( found_at, search.length() , replace );
cout << text << endl;
found_at = text.find( search, found_at + search.length() );
}

cout << text << endl;
}
Best regards

Kai-Uwe Bux
Nov 10 '05 #5
* in*****@gmail.c om:

These days every post here smells way too much like homework, but I'll
give you the benefit of the doubt :D.


Unless this Phlip is someone else than the regular Phlip, we can safely
discount the possibility of a homework question.

What surprises me is that Phlip wants to do this in C++, not in Ruby...

Anyways, for efficiency, I think a two-pass approach is indicated: first
find number of occurrences of the search pattern to be replaced, then
allocate buffer, then copy over with search pattern replaced. For an
original string of length n, that reduces the time from O(n^2) to O(n).
Of course the real decider would be to measure, measure, measure,
because two-pass might much _slower_ for short (typical?) strings.

How to do the searching efficiently depends on what's known about the
data.

For a long string the skipping algorithm used in various grep's could be
employed, and likewise for doing the same replacement on a multitude of
strings, but for a single global replacement on a short string using
skipping might be counter-productive because of the setup time. And to
bring that back on-topic (namely, C++), Phlip might be well advised --
or not -- to check out the facilities of the first standard library
Technical Report, the TR1. As I recall there is some regexp in there.

--
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?
Nov 10 '05 #6

Kai-Uwe Bux wrote:
in*****@gmail.c om wrote:
Note that "replace" has one more letter than "search", so you can't do an
inplace substitution.
Why not? Watch me :D

#include <string>
#include <iostream>

using namespace std;

int main()
{
const string search = "search";
const string replace = "replace";

string text = " able search baker search charlie ";

string::size_ty pe found_at = text.find( search );
while( string::npos != found_at )
{
text.replace( found_at, search.length() , replace );
found_at = text.find( search, found_at + search.length() );
}

cout << text << endl;
}


Why not? here is why:

#include <string>
#include <iostream>

using namespace std;

int main()
{
const string search = "search";
const string replace = "devious_search _replacement";

string text = " able search baker search charlie ";

string::size_ty pe found_at = text.find( search );
while( string::npos != found_at )
{
text.replace( found_at, search.length() , replace );
cout << text << endl;
found_at = text.find( search, found_at + search.length() );


You spotted my mistake here. This should read:
found_at = text.find( search, found_at + replace.length( ) );
}

cout << text << endl;
}

Cheers,
Andre

Nov 10 '05 #7

"Phlip" <ph******@yahoo .com> wrote in message
news:hn******** ********@newssv r17.news.prodig y.com...
C++ers:

Here's an open ended STL question. What's the smarmiest most templated way
to use <string>, <algorithms> etc. to turn this:

" able search baker search charlie "

into this:

" able replace baker replace charlie "

Note that "replace" has one more letter than "search", so you can't do an
inplace substitution.

An alternate prize goes to whoever provides an efficient way (that doesn't
use simple things like character pointers and buffers and C things ;).


heh this is in Haskell:

searchReplace srch rpls xs = unwords $ searchReplace' srch rpls $ words xs
searchReplace' _ _ [] = []
searchReplace' srch rpls (x:xs) | x==srch = rpls:searchRepl ace' srch rpls
xs
| otherwise = x:searchReplace ' srch rpls xs
C++:
string searchReplace(s tring search,string replace,string xs)
{
istringstream is(xs);string tmp;
ostringstream os;
while(is>>tmp)i f(tmp==search)o s<<replace;els e os<<tmp;
return os.str();
}

I don't know which STL algorithm is equialent of this.

Greetings, Bane.
Nov 10 '05 #8

"Branimir Maksimovic" <bm***@eunet.yu > wrote in message
news:dk******** **@news.eunet.y u...

C++:
string searchReplace(s tring search,string replace,string xs)
{
istringstream is(xs);string tmp;
ostringstream os;
while(is>>tmp)i f(tmp==search)o s<<replace;els e os<<tmp; while(is>>tmp)
{
if(tmp==search) os<<replace;els e os<<tmp;
os<<' ';
}
return os.str();
}


Of course this is only if spaces are not important.

Greetings, Bane.
Nov 10 '05 #9
Kai-Uwe Bux wrote:
Ok, it's not templated; but it is short:
I kind'a meant "STL-obsessed". Not just templated.
void replace_all ( std::string & str,
std::string const & pattern,
std::string const & replacement ) {
std::string::si ze_type start = str.find( pattern, 0 );
while ( start != str.npos ) {
str.replace( start, pattern.size(), replacement );
start = str.find( pattern, start+replaceme nt.size() );
}
}


Great; everyone posted a loop with a find!

My colleague came up with this. Somehow:

stringstream ss;
ostream_iterato r<string> outIterator(ss) ;

transform( m_str.begin(), m_str.end(), outIterator,
swap_character( asciiChar, substituteStrin g) );

m_str = ss.str();

Note that it's a member of some method that transforms a member string
m_str, and that it searches for a single character and replaces it with
a string.

Could one upgrade that to work on a string?

Is its performance profile more or less "guaranteed " than the entries
so far?

The question ain't in Ruby because the answer is too danged simple -
Regular expressions are built-in, overhead and all...

--
Phlip

Nov 10 '05 #10

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

Similar topics

1
8712
by: Les Juby | last post by:
A year or two back I needed a search script to scan thru HTML files on a client site. Usual sorta thing. A quick search turned up a neat script that provided great search results. It was fast, returned the hyperlinked page title, filename, and the body txt (30 preceding and following words) in context with the search word highlighted. ...
10
3121
by: pembed2003 | last post by:
Hi all, I asked this question in the C group but no one seems to be interested in answering it. :-( Basically, I wrote a search and replace function so I can do: char source = "abcd?1234?x"; char search = '?'; char* replace = "***"; char* result = search_and_replace(source,search,replace);
5
2623
by: pembed2003 | last post by:
Hi all, I need to write a function to search and replace part of a char* passed in to the function. I came up with the following: char* search_and_replace(char* source,char search,char* replace){ char* result; size_t l = strlen(source), r = strlen(replace), i; int number_of_replaces = 0; for(i = 0; i < l; i++){ if(source == search)
32
14797
by: tshad | last post by:
Can you do a search for more that one string in another string? Something like: someString.IndexOf("something1","something2","something3",0) or would you have to do something like: if ((someString.IndexOf("something1",0) >= 0) || ((someString.IndexOf("something2",0) >= 0) ||
2
5078
by: Dennis | last post by:
I am trying to implement a "Find and Replace" dialog that allows using wildcards in the find string, much like the Find and Replace Dialogs in Ms Word, etc. Are there any references or examples on this. I have tried using the Like comparision operator but about all I can do with it is replace a whole string that contains the wildcard search...
2
5074
by: Ola K | last post by:
Hi guys, I wrote a script that works *almost* perfectly, and this lack of perfection simply puzzles me. I simply cannot point the whys, so any help on it will be appreciated. I paste it all here, the string at the beginning explains what it does: '''A script for MS Word which does the following: 1) Assigns all Hebrew italic characters...
9
2240
by: tomjones75 | last post by:
dear community, i want to search the content of all fields in one table in a access database. it already works for the content of one field in the table. please take a look at the code in the resultpage: <%
14
2252
by: Simon Gare | last post by:
Hi, have a search.asp page with results.asp page drawing data from an SQL db, problem is the user has to type the whole field value into the search box to retrieve the value on results.asp, what I need is to type in just a few characters e.g. at the moment to search for all pickups at Heathrow Terminal 1 the user has to type in Heathrow...
1
7523
Merlin1857
by: Merlin1857 | last post by:
How to search multiple fields using ASP A major issue for me when I first started writing in VB Script was constructing the ability to search a table using multiple field input from a form and having the sql statement dynamically built according to the input provided by the user. I have used the method described here hundreds of times it is...
0
7868
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
7792
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
8149
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
8304
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...
1
7899
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...
0
8175
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6553
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...
0
5364
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...
1
1403
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.