francops henri
francops henri

Reputation: 517

how to replace the exact word by another in a list?

I have a list like :

I would like to replace fg, fgu, and fguh by "fguhCool" I already tried something like this :

            foreach (var ignore in NameToPoulate)
        {
            tempo = ignore.Replace("fg", "fguhCool");
            NameToPoulate_t.Add(tempo);
        }

But then "fgu" become "fguhCoolu" and "fguh" become "fguhCooluh" is there are a better idea ?

Thanks for your help.

Upvotes: 0

Views: 279

Answers (3)

Tormod
Tormod

Reputation: 4583

I assume that this is a homework assignment and that you are being tested for the specific algorihm rather than any code that does the job.

This is probably what your teacher has in mind:

Students will realize that the code should check for "fguh" first, then "fgu" then "fg". The order is important because replacing "fg" will, as you have noticed, destroy a "fguh".

This will by some students be implemented as a loop with if-else conditions in them. So that you will not replace a "fg" that is within an already replaced "fguhCool".

But then you will find that the algorithm breaks down if "fg" and "fgu" are both within the same string. You cannot then allow the presence of "fgu" prevent you to check for "fg" at a different part of the string.

The answer that your teacher is looking for is probably that you should first locate "fguh", "fgu" and "fg" (in that order) and replace them with an intermediary string that doesn't contain "fg". Then after you have done that, you can search for that intermediary string and replace it with "fguhCool".

Upvotes: 3

mgibsonbr
mgibsonbr

Reputation: 22007

Use a regular expression:

Regex.Replace("fg(uh?)?", "fguhCool");

An alternative would be replacing the long words for the short ones first, then replacing the short for the end value (I'm assuming all words - "fg", "fgu" and "fguh" - would map to the same value "fguhCool", right?)

tempo = ignore
    .Replace("fguh", "fg")
    .Replace("fgu", "fg")
    .Replace("fg", "fguhCool");

Obs.: That assumes those words can appear anywhere in the string. If you're worried about whole words (i.e. cases where those words are not substrings of a bigger word), then see @Joey's answer (in this case, simple substitutions won't do, regexes are really the best option).

Upvotes: 0

Joey
Joey

Reputation: 354854

You could use regular expressions:

Regex.Replace(@"\bfg\b", "fguhCool");

The \b matches a so-called word boundary which means it matches the beginnnig or end of a word (roughly, but for this purpose enough).

Upvotes: 0

Related Questions