1

How do I replace word in string except first occurrence using c#

for example

string s= "hello my name is hello my name hello";

replace hello with x

output should be string news = "hello my name is x my name x";

I tried like works fine

string originalStr = "hello my hello ditch hello";
        string temp = "hello";
        string str = originalStr.Substring(0, originalStr.IndexOf(temp) + temp.Length);
        originalStr = str + originalStr.Substring(str.Length).Replace(temp, "x");

can I have Regex expression for above code ?

3
  • It should be first occurrence or word without space? Commented Aug 5, 2014 at 9:54
  • Is this poor sample data or poor exlanation? The first word is not "llo" so why should it be replaced at all? Or don't want you to replace complete words but also substrings? Commented Aug 5, 2014 at 9:55
  • updated quaetion with clear data Commented Aug 5, 2014 at 9:57

3 Answers 3

5

This will do it for a general pattern:

var matchPattern = Regex.Escape("llo");
var replacePattern = string.Format("(?<={0}.*){0}", matchPattern);
var regex = new Regex(replacePattern);
var newText = regex.Replace("hello llo llo", "x");

If you want to only match and replace whole words, edit your pattern accordingly:

var matchPattern = @"\b" + Regex.Escape("hello") + @"\b";
Sign up to request clarification or add additional context in comments.

Comments

2

Try this:

string pat = "hello";
string tgt = "x";
string tmp = s.Substring(s.IndexOf(pat)+pat.Length);
s = s.Replace(tmp, tmp.Replace(pat,tgt));

tmp is the substring of the original string starting after the end of first occurrence of the pattern to be replaced (pat). We then replace pat with the desired value (tgt) within this substring, and replace the substring in the original string with this updated value.

Demo

3 Comments

This won't work in all cases. Try with this input string: string s= " my hello my hello my hello my hello my hello my hello my hello my";
My code is also working perfect in above condition :)
@ashish Feel free to use my code if your input is guaranteed to be like the sample. But Lasse has pointed out a failed case, and you need to understand that it must also be handled correctly.
1

Do you need regex? You could use this little LINQ query and String.Join:

int wordCount = 0;
var newWords = s.Split()
    .Select(word => word != "hello" || ++wordCount == 1 ? word : "x");
string newText = string.Join(" ", newWords);

But note that this will replace all white-spaces (even tabs or newlines) with a space.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.