0

I'm using C# stringBuilder to replace string with the best performance, the the replace is never finish without informing the user how many replacements were made, but the Replace() method only return the stringBuilder instance, also I can't find any method in stringBuilder helping to count the replacements.

So is there anyway to find out how many replacements were made? Thank for reading :)

123iamking
  • 2,387
  • 4
  • 36
  • 56

1 Answers1

1

Just do a count for string before running the replace. You'd have to introduce your own extension method or LINQ query.

Example extension method:

public static int OccurencesOf(this string str, string val)
{  
int num_occurrences = 0;
int num_startingIndex = 0;

while ((num_startingIndex = str.IndexOf(val, num_startingIndex)) >= 0) 
{
    ++num_occurrences;
    ++num_startingIndex;
}

return num_occurrences;
} 
Joe Healy
  • 5,769
  • 3
  • 38
  • 56
  • Is it waste the stringBuilder effort? I mean the stringBuilder was made to reduce the time the string object has to be made, if I use this I have to make string obj which is immutable. – 123iamking May 15 '16 at 01:32
  • 1
    There is no way to do what you want with pure stringbuilder. So its going to be inefficient, yes. – Joe Healy May 15 '16 at 14:07
  • I think I'll research how StringBuilder was made and add the count replacements function, do you think it possible? – 123iamking May 16 '16 at 04:14