0

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?

user1928346
  • 513
  • 6
  • 21
  • "How should I write the code to do the replacement?". What have you tried? Is this an issue you are actually facing (note the FAQ says: "You should only ask practical, answerable questions based on actual problems that you face."). – Oded Jan 07 '13 at 13:38
  • What have you tried so far? Have you read anything about string search and replace in C#? I mean, it's a fairly well covered topic. No doubt google returns no less than a hundred page that cover it. – Pete Jan 07 '13 at 13:38
  • possible duplicate of [How can I replace a specific word in C#?](http://stackoverflow.com/questions/884759/how-can-i-replace-a-specific-word-in-c) – Jon B Jan 07 '13 at 13:43
  • @JonB: This question is slightly different. He wants to replace a word combination with another word combination without replacing parts of a word. So each string must be a whole word and the order matters (i assume). – Tim Schmelter Jan 07 '13 at 13:50

4 Answers4

1

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"

Community
  • 1
  • 1
Dhaval
  • 2,801
  • 20
  • 39
1

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.

semao
  • 1,757
  • 12
  • 12
0

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

Community
  • 1
  • 1
Marcus
  • 8,230
  • 11
  • 61
  • 88
-1

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?

Community
  • 1
  • 1
Alex
  • 5,971
  • 11
  • 42
  • 80
  • That would fail if the word/phrase appears at the beginning or end of the string, or if it's followed by punctuation. – Jon B Jan 07 '13 at 13:42