473,395 Members | 1,761 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,395 software developers and data experts.

How to replace many substrings?

Is there a well-known algorithm for replacing many substrings in a
string? For example, I'd like to take the string "abc def ghi jkl mno
pqr" and replace, say, every instance of "abc", "ghi", and "mno" with
another value.

Of course the brute-force approach is straight forward. Just iterate
over the full string N times (once for "abc", "ghi", and "mno"), find
all instances, and replace them using the normal std::string member
functions. Of course this seems terribly inefficient as I will have to
traverse my string many times (in my real applications I may have to
replace tens of strings).

I imagine this sort of thing comes up a lot in parsers, but I'm not
sure where to begin.

Thanks.

Derek

Jul 23 '05 #1
4 4639
sp**@grog.net wrote:
Is there a well-known algorithm for replacing many substrings in a
string? For example, I'd like to take the string "abc def ghi jkl mno
pqr" and replace, say, every instance of "abc", "ghi", and "mno" with
another value.

Of course the brute-force approach is straight forward. Just iterate
over the full string N times (once for "abc", "ghi", and "mno"), find
all instances, and replace them using the normal std::string member
functions. Of course this seems terribly inefficient as I will have to
traverse my string many times (in my real applications I may have to
replace tens of strings).

I imagine this sort of thing comes up a lot in parsers, but I'm not
sure where to begin.


Begin by understanding what you need.

What should happen if the first string when replaced with whatever else
creates another case of the second string:

source: "abc_afc_abd"
replace "ab" with "ff" _and_ "fc" with "bb"

If you perform "search for all and create the set of locations, then
replace all in one swoop and never come back" algorithm, you get

"ab" locations: { 0, 8 }
"fc" locations: { 5 }

Replacing...

result: "ffc_abb_ffd"

Finished and done? But you still have an "ab" and an "fc" in there...
You come back and do it again:

"ab" locations: { 4 }
"fc" locations: { 1 }

Replacing...

result: "fbb_ffb_ffd"

Whew!...

If you do it "all replacements of one, then all replacements of the
other", you'd have

After replacing of "ab" in the entire string: "ffc_afc_ffd"
After replacing of "fc" in the new string: "fbb_abb_ffd"

As you can see the result is not the same as with the first approach.
You may need to come back for the "ab" again and then you get

After the second scan for "ab": "fbb_ffb_ffd"
After the second scan for "fc": "fbb_ffb_ffd"

Finally!

Now, we're not even talking about possible _overlapping_ of the search
strings...

I am showing it to you to explain why you need to specify better what
you're looking for in such algorithm.

V
Jul 23 '05 #2
> Begin by understanding what you need.

You are quite right to point out that my original post was not very
specific about what I need. What I need is an algorithm that does all
replacements at once, in one pass. As you pointed out, this one-pass
approach can leave the job unfinished:
source: "abc_afc_abd"
replace "ab" with "ff" _and_ "fc" with "bb" .... result: "ffc_abb_ffd"
Finished and done? But you still have an "ab" and an "fc" in there...


I need this algorithgm for the purpose of obfuscating sensitive
information in my application's logs. Substrings will be replaced with
auto-generated identifiers that will never match a portion of the
original string. Thus "ab" might be replaced with "~D45~", which I know
never appears in the original string. So a one-pass algorithm is good
enough.

As for overlap, I can also assume it doesn't happen. In short, it's the
one-pass aspect of the algorithm I want to understand. I have enough
control to define most edge cases out of existence. I just want to
avoid making 20-30 passes through the string to replace all 20-30
substrings.

Thanks for your reply,
Derek

Jul 23 '05 #3
sp**@grog.net wrote:
Is there a well-known algorithm for replacing many substrings in a
string? For example, I'd like to take the string "abc def ghi jkl mno
pqr" and replace, say, every instance of "abc", "ghi", and "mno" with
another value.

Of course the brute-force approach is straight forward. Just iterate
over the full string N times (once for "abc", "ghi", and "mno"), find
all instances, and replace them using the normal std::string member
functions. Of course this seems terribly inefficient as I will have to
traverse my string many times (in my real applications I may have to
replace tens of strings).

I imagine this sort of thing comes up a lot in parsers, but I'm not
sure where to begin.


There is a "standard" approach. You should look at "flex" (or lex). It
just so happens that I have written somthing recently that I can share
with you.

I have attached somthing that should work (though probably much slower
than flex or lex) but it has the property that it has more or less the
same performance regardless of the number of strings you're matching.

The attached code not general. It will only match strings, not classes
of strings or regular expressions (like lex or flex) but because of
that, it has the property that you can add new terminals (strings to
check for) dynamically without any post-processing.

The attached code requires that you construct a "traverser" which can
simply wrap a string or a std::istream object so it should be able to
read from just about anything you can think of. I've used it in an old
editor that needed a better way of dealing with escape sequences.

The basic algorithm is a simple state machine. (DFA) Every character
that comes in is a transition on in the state machine, if there is no
transition for a given character, then the sequence is deemed to be
"invalid" or simply not one of the "terminals" you're looking for in
which case you need to pop off one character in the "push-back" buffer
and try again. In your case, the characters that are "popped off" are
untouched parts of the stream.

Another possible approach and probably very fast, is to use a modified
Burrows-Wheeler transform. Using the first phase of the BW transform,
you create a list of pointers to sorted substrings of the original
string. Once you do that, checking with your list of strings to
substitute is a modified merge sort, where you match the sub-strings
with the "terminals" you're looking for, and then you re-sort the
pointers that match the original order. Then it's a simple matter of
scanning the list of remaining pointers and perfoming the substitution
taking into account overlap and end-conditions.

Enjoy

Jul 23 '05 #4
Thanks for the great info and source code. This is exactly the kind of
thing I was looking for.

Jul 23 '05 #5

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

Similar topics

5
by: K.Simon | last post by:
Hello, it's very often neccessary to replace strings or a single character in my stylesheets. My solution looks awful and very long. Now i thought to solve this with an array like structure but...
24
by: Wim Roffal | last post by:
Is there a possibility to do a string replace in javascript without regular experessions. It feels like using a hammer to crash an egg. Wim
4
by: Prasad S | last post by:
Hello I wish to replace all the characters in a string except those which are inside '<' & '>' characters. And there could be multiple occurences of < & > within the string. e.g. string =...
13
by: M | last post by:
Hi, I've searched through the previous posts and there seems to be a few examples of search and replacing all occurrances of a string with another string. I would have thought that the code...
9
by: C3 | last post by:
I have to process some data in C that is given to me as a char * array. I have a fairly large number of substrings (well, they're not actually printable, but let's treat them as strings) that I...
7
by: f pemberton | last post by:
I have a string (xdata) and theres a newline after every 17 characters of the string. I was wondering how I can replace multiple substrings multiple times within a string? To put it another way,...
1
by: roots_of_culture | last post by:
Hi all, VB novice bear with me... trying to build myself a template in Outlook to make life easier I am aquiring multiple subtrings from the user and want to replce one substring in a outlook...
8
by: Warren Moxley | last post by:
Hi there, i've been searching for a C String search and replace function. I need to find all occurrences of " " in a char* array, and replace them with another char, I know how to do this in...
3
by: Ned White | last post by:
Hi All, To replace some substrings in a string value, i use Regex.Replace method mulptiple times like; strmemo = "new Data for user; Name:@@Name , Surname:@@Surname, Address:@@Address";...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
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...
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
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
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...
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...

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.