简体   繁体   中英

calculate number of repetition of character in string in c#

how can I calculate the number of repetition of character in string in c# ? example I have sasysays number of repetition of character 's' is 4

Here is a version using LINQ (written using extension methods):

int s = str.Where(c => c == 's').Count();

This uses the fact that string is IEnumerable<char> , so we can filter all characters that are equal to the one you're looking for and then count the number of selected elements. In fact, you can write just this (because the Count method allows you to specify a predicate that should hold for all counted elements):

int s = str.Count(c => c == 's');

Another option is:

int numberOfS = str.Count('s'.Equals);

This is a little backwards - 's' is a char, and every char has an Equals method, which can be used as the argument for Count .
Of course, this is less flexible than c => c == 's' - you cannot trivially change it to a complex condition.

s.Where(c => c == 's').Count()

给定s是一个字符串,你正在寻找's'

for(int i=0; i < str.Length; i++) { 
    if(str[i] == myChar) {
        charCount++;
    }
}

A more general solution, to count number of occurrences of all characters :

var charFrequencies = new Dictionary<char, int>();
foreach(char c in s)
{
    int n;
    charFrequencies.TryGetValue(c, out n);
    n++;
    charFrequencies[c] = n;
}

Console.WriteLine("There are {0} instances of 's' in the string", charFrequencies['s']);
        string s = "sasysays ";
        List<char> list = s.ToList<char>();
        numberOfChar = list.Count<char>(c => c=='s');

Try this code :

namespace Count_char
{
    class Program
  {
    static void Main(string[] args)
    {
        string s1 = Convert.ToString(Console.ReadLine());
        for (int i = 97; i < 123; i++)
        {
            string s2 = Convert.ToString(Convert.ToChar(i));

            CountStringOccurrences(s1, s2);
        }


        Console.ReadLine();
    }
    public static void CountStringOccurrences(string text, string pattern)
    {

        int count = 0;
        int i = 0;
        while ((i = text.IndexOf(pattern, i)) != -1)
        {
            i += pattern.Length;
            count++;

        }
        if (count != 0)
        {
            Console.WriteLine("{0}-->{1}", pattern, count);
        }

    }
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM