1

Is there a method to get the number of replacements using .Replace("a", "A"); ?

Example:

String string_1 = "a a a";
String string_2 = string_1.Replace("a", "A"); 

In this case, the output should be 3, because a was replaced with A 3 times.

Isamu
  • 41
  • 1
  • 9

3 Answers3

3

You can get the count using .Split function :

 string_1.Split(new string[] { "a" }, StringSplitOptions.None).Length-1;

After splitting the string we will get one item more. Because, .Split function returns a string array that contains the substrings in this string that are delimited by elements of a specified string array. So, the Length property's value will be n+1.

Farhad Jabiyev
  • 26,014
  • 8
  • 72
  • 98
3

You cannot do this directly with string.Replace, but you could use the string.IndexOf to search for your string until it doesn't find a match

int counter = 0;
int startIndex = -1;
string string_1 = "a a a";
while((startIndex = (string_1.IndexOf("a", startIndex + 1))) != -1)
    counter++;
Console.WriteLine(counter);

If this becomes of frequent use then you could plan to create an extension method

public static class StringExtensions
{
     public static int CountMatches(this string source, string searchText)
     {

        if(string.IsNullOrWhiteSpace(source) || string.IsNullOrWhiteSpace(searchText))
           return 0;

         int counter = 0;
         int startIndex = -1;
         while((startIndex = (source.IndexOf(searchText, startIndex + 1))) != -1)
             counter++;
         return counter;
     }
}

and call it with

int count = string_1.CountMatches("a");

The advantages of IndexOf are in the fact that you don't need to create an array of strings (Split) or an array of objects (Regex.Matches). It is just a plain vanilla loop involving integers.

Steve
  • 213,761
  • 22
  • 232
  • 286
1

You can use the Regex.Matches method to find out what would be replaced. Use the Regex.Escape method to escape the string if it would contain any characters that would be treated specially as a regular expression.

int cnt = Regex.Matches(string_1, Regex.Escape("a")).Count;
Guffa
  • 687,336
  • 108
  • 737
  • 1,005