-1

I know how to replace a specific word with another one in paragraph or text file using following code:

String output = input.Replace("oldvalue","newvalue");

But i confused with replacing set of words replacing . I'm having nearly 1000 words to replace. E.g.:

" aback " => " ashamed ",
" abacus " => " abacus ",
" abaft " => " aback ",
" abandon " => " carelessness ",
" abandoned " => " alone ",

So if the paragraph contains the word aback i want to replace it with ashamed like for every words. How can we do that? Can anyone give me an idea?

yasmuru
  • 1,178
  • 2
  • 20
  • 42
  • If limited amount of words, put a for loop around the replace and perform it once per word. If many words, parse the string into words/parts and for each part look up if there is a replacement. Build the new string using the (replaced) parsed parts. – PHeiberg Sep 30 '13 at 05:19

3 Answers3

11

You can write an extension method like this

public static string ReplaceSetOfStrings(this string input, Dictionary<string, string> pairsToReplace)
{
    foreach (var wordToReplace in pairsToReplace)
    {
        input = input.Replace(wordToReplace.Key, wordToReplace.Value);
    }
    return input;
}

In the above method Dictionary key will contain the word that needs to be replaced with the word to be replcaed with in the value.

Then you can call it like this

Dictionary<string,string> pairsToBeReplaced = new Dictionary<string,string>();
pairsToBeReplaced.Add(" aback "," ashamed ");
input.ReplaceSetOfStrings(pairsToBeReplaced);
Habib
  • 219,104
  • 29
  • 407
  • 436
Ehsan
  • 31,833
  • 6
  • 56
  • 65
1

Since you are trying to replace actual words, it is probably important that you find only complete words (rather than partial words), even if they are at the beginning of a sentence (i.e. capitalized) or end of a sentence (e.g. have a period after them). This calls for a regular expression because you can tell it to only look for whole words with the \b.

// This version will replace whole words (you don't need spaces around each one)
string ReplaceWords(string input, Dictionary<string, string> replacements)
{
    return Regex.Replace(
               input,
               @"\b(" 
                   + String.Join("|", replacements.Keys.Select(k => Regex.Escape(k)))
                   + @")\b", // pattern
               m => replacements[m.Value] // replacement
               );
}

// This version will replace capitalized words if the key is all lowercase
string ReplaceWords(string input, Dictionary<string, string> replacements)
{
    return Regex.Replace(
               input,
               @"\b(" 
                   + String.Join("|", replacements.Keys.Select(k => Regex.Escape(k)))
                   + @")\b", // pattern
               m => replacements[m.Value], // replacement
               RegexOptions.IgnoreCase);
}

private static string ReplaceWord(string word, Dictionary<string, string> replacements)
{
    string replacement;
    // see if word is in the dictionary as-is
    if (replacements.TryGetValue(word, out replacement))
        return replacement;
    // see if the all-lowercase version is in the dictionary
    if (replacements.TryGetValue(word.ToLower(), out replacement))
    {
        // if the word is all uppercase, make the replacement all uppercase
        if (word.ToUpper() == word)
            return replacement.ToUpper();
        // if the first letter is uppercase, make the replacement's first letter so
        if (char.IsUpper(word[0]))
            return char.ToUpper(replacement[0]) + replacement.Substring(1);
        // otherwise just return the replacement as-is
        return replacement;
    }
    // no replacement found, so don't replace
    return word;
}

If the keys in the dictionary don't change between calls, you can compile the Regex as a likely optimization.

Gabe
  • 84,912
  • 12
  • 139
  • 238
  • thanks for your answer and its working cool . And Sorry i have edited your answer for avoiding some errors :) – yasmuru Sep 30 '13 at 06:41
0

You can replace like below : Stolen from Here

StringBuilder sb = new StringBuilder("11223344");

    string myString =
        sb
          .Replace("1", string.Empty)
          .Replace("2", string.Empty)
          .Replace("3", string.Empty)
          .ToString();

or You can do like this also : Stolen from Here

// Define name/value pairs to be replaced.
var replacements = new Dictionary<string,string>();
replacements.Add("<Name>", client.FullName);
replacements.Add("<EventDate>", event.EventDate.ToString());

// Replace
string s = "Dear <Name>, your booking is confirmed for the <EventDate>";
foreach (var replacement in replacements)
{
   s = s.Replace(replacement.Key, replacement.Value);
}
Community
  • 1
  • 1
RajeshKdev
  • 6,365
  • 6
  • 58
  • 80