Example of the number of occurrences of a string in a C # statistic string

Source: Internet
Author: User
Tags foreach

Example 1

  code is as follows copy code

To compute the occurrence of a substring in a string Number of times, is there a good way?
///<summary>
///calculates the number of occurrences of a string substring
///</summary>
///<param "str" > String name=
///<param name= "substring" > substring </param>
///<returns> occurrences </returns>
Static int Substringcount (string str, string substring)
{
if (str. Contains (substring))
{
String strreplaced = str. Replace (substring, "");
Return (str. length–strreplaced.length)/substring. Length;
}

return 0;
}
int count = Substringcount ("Ddddfdfhgfjghjhgjghjhjhjhjhj", "GH");


Example 2 hash table

The code is as follows Copy Code

Hashtable ht = new Hashtable ();
string sr = "AAABBCDDDDD";
Char[] cr = Sr. ToCharArray ();
foreach (char ch in CR)
{
if (HT. ContainsKey (CH))
{
int i = (int) ht[ch];
Ht. Remove (CH);
Ht. ADD (CH, ++i);
}
Else
Ht. ADD (CH, 1);
}
foreach (DictionaryEntry dicentry in HT)
{
Console.WriteLine ("{0} appears {1} times", Dicentry.key, Dicentry.value);
}
ArrayList alist = new ArrayList (HT. Values);
Alist. Sort ();
Object o = (object) alist[alist. COUNT-1];
foreach (DictionaryEntry dicentry in HT)
{
if (Dicentry.value = O)
{
String str = dicEntry.Key.ToString ();
Console.WriteLine ("The most frequent characters: {0}, total {1} times", str, o.tostring ());
Break
}
}
Console.ReadLine ();

Example 3 LINQ

The code is as follows Copy Code

string s = "AAABCCCCEF";
Char[] C = S.tochararray ();
var cc = C.GROUPBY (e => e). OrderByDescending (e => e.count ()). ToList ();
for (int i = 0; i < cc. Count; i++)
{
Console.WriteLine ("{0}t{1}", Cc[i]. Key.tostring (), Cc[i]. Count (). ToString ());
}
var CCC = C.groupby (e => e). OrderByDescending (e => e.count ()). A (). ToList ();

Console.WriteLine ("{0}" appears {1} times!) ", Ccc[0]. ToString (), CCC. Count (). ToString ());
Console.readkey ();

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.