user1928346
user1928346

Reputation: 513

C# Multiple Word Replacement Issue

Consider the case where I want every occurrence of the phrase "hello world" in an article to be replaced with "I love apple". How should I write the code to do the replacement?

I am aware that I could simply use Replace function to do the replacement but it is not the most ideal way to do so (if I specify to replace the word "or" it will also do the replacement for the word "for" etc). Is there any other way I can do to achieve what I want?

Upvotes: 0

Views: 341

Answers (4)

semao
semao

Reputation: 1757

You can try using Regular Expressions with lookbehind:

String urstring = Regex.Replace(urstring,"(?<=\W)or|^or","SS")

This will replace all "or" occurrences that are NOT preceded by a letter or digit.

Upvotes: 1

Alex
Alex

Reputation: 6149

Try using regex like in here:

How can I replace a specific word in C#?

or here:

How can I replace specific word in c# with parenthesis?

Upvotes: -1

Dhaval
Dhaval

Reputation: 2861

i think you can use regular expresion

using System;
using System.Text.RegularExpressions;
public class Test
{
   public static void Main()
   {
       string input = "doin some replacement";
       string pattern = @"\bhello world'\b";
       string replace = "I love apple";
       string result = Regex.Replace(input, pattern, replace);        
    }
}

following link might be helpful

Way to have String.Replace only hit "whole words"

Upvotes: 1

Marcus
Marcus

Reputation: 8659

Use Regular Expressions. This has already been covered, please consult the following:

  1. How can I replace a specific word in C#?

  2. replace text in a string with .net regexp

Upvotes: 0

Related Questions