Dilip
Dilip

Reputation: 747

Get all The index of Any Word in the String

I have one String , Which contain Word more Than one time .. I want to find Each occurrence of that word one by one and need To add some other word after That ..

Example -

<start>
<child1>
.
.
.
<start>
<child2>
..

and So On ..

i tried .

int count = Regex.Matches(StrRemoveWrongData, @"<start>").Count;

its giving me count , there is any thing where we can go to every occurrence one by one . and add new word below that ..

Upvotes: 0

Views: 1873

Answers (2)

L.B
L.B

Reputation: 116108

According to your title, to get all the index;

 var indexList = Regex.Matches(StrRemoveWrongData, @"<start>").Cast<Match>()
                    .Select(m => m.Index)
                    .ToList();

If your replacement algorightm is more complex than a simple then string you can use the overload of Regex.Replace

int count = 1;
var newstr = Regex.Replace(StrRemoveWrongData, @"<start>", 
                       m => { 
                           //Do some work
                           return String.Format("<child{0}>",count++);
                       }
              );

Upvotes: 2

Sidharth Mudgal
Sidharth Mudgal

Reputation: 4264

You can simply do: StrRemoveWrongData = StrRemoveWrongData.Replace(@"<start>", newString);

Upvotes: 2

Related Questions