How to count the number of occurrences of some symbols?

c#, string

Solution

I would use a Regular Expression to find anything that looks like a variable.

If your variables are percent-sign, any-word-character, percent-sign, then the following should work:

string input = "The name of my dog is %x% and he has %y% years old.";

// The Regex pattern: \w means "any word character", eq. to [A-Za-z0-9_]
// We use parenthesis to identify a "group" in the pattern.

string pattern = "%(\w)%";     // One-character variables
//string pattern ="%(\w+)%";  // one-or-more-character variables

// returns an IEnumerable
var matches = Regex.Matches(input, pattern);

foreach (Match m in matches) { 
     Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
     var variableName = m.Groups[1].Value;
}

MSDN:

- `Regex.Matches`

Problem

In my program, you can write a string where you can write variables. For example: The name of my dog is %x% and he has %y% years old. The word where I can replace is any between `%%`. So I need to get a function where tells which variables I have in that string. ``` GetVariablesNames(string) => result { %x%, %y% } ```

Original source