PYJTER
PYJTER

Reputation: 91

Search for an exact phrase and change

I have a problem with changing values ​​into a string. I have three values, e.g. a, aa, aaa

StringBuilder builders = new StringBuilder(string);
builders.Replace("a", "ab");
builders.Replace("aa", "bab");
builders.Replace("aaa", "bba");
string new_string = builders.ToString();

How to do it to find exactly the value of 'aaa' because for this value both the condition of 'a' and 'aa' is also fulfilled.

Upvotes: 0

Views: 42

Answers (2)

Jonathan Wood
Jonathan Wood

Reputation: 67223

The easiest way is to replace the long tokens first.

It looks like your replacement strings also contain "a". So you might need to replace them with a temporary string (one that is unlikely to occur in the original text), and then convert to the target string after you've processed them all.

The only way to intelligently only replace "a" without replacing "aa" is to parse each character in the text to determine how long each token is. It's not that hard, but a lot more work than calling Replace().

Upvotes: 1

Zohar Peled
Zohar Peled

Reputation: 82474

Just do the replaces from the longest substring to the shortest one:

builders.Replace("aaa", "bba");
builders.Replace("aa", "bab");
builders.Replace("a", "ab");

Upvotes: 1

Related Questions