Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count the number of occurrences of some symbols?

Tags:

string

c#

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% }
like image 812
Darf Zon Avatar asked Dec 09 '12 15:12

Darf Zon


People also ask

How do you count the number of symbols in a cell?

To use the function, enter =LEN(cell) in the formula bar and press Enter. In these examples, cell is the cell you want to count, such as B1. To count the characters in more than one cell, enter the formula, and then copy and paste the formula to other cells.

How do I count a specific symbol in Excel?

The LEN function is fully automatic. In the example, the formula in the active cell is: = LEN ( B5 ) The LEN function simply counts all characters that appear in a cell. All characters are counted, including space characters, as you can see in cell...


1 Answers

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
like image 99
Jonathon Reinhart Avatar answered Sep 19 '22 01:09

Jonathon Reinhart