C#:統計字符串中每個字符的個數


具體代碼如下:

 1 namespace demo
 2 {
 3     public class Program
 4     {
 5         static void Main(string[] args)
 6         {
 7             string str = "hi,good morning.";
 8             Console.WriteLine($"字符串:{str}");
 9             Dictionary<char, int> dic = Count(str);
10             foreach(var c in dic)            
11                 Console.WriteLine($" '{c.Key}':{c.Value}");            
12             Console.ReadKey();
13         }
14         static Dictionary<char,int> Count(string str)
15         {
16             Dictionary<char, int> dic = new Dictionary<char, int>();
17             char[] chars = str.ToArray();
18             foreach(char c in chars)
19             {
20                 if (dic.ContainsKey(c))
21                     dic[c]++;
22                 else
23                     dic.Add(c, 1);
24             }
25             return dic;
26         }
27     }
28 }

執行結果:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM