本帖最后由 猫咪不吃糖 于 2013-10-16 01:14 编辑
有个小bug,RepeatChar 初值是空格,这个不能null,{:soso_e101:} ;- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace Dic1
- {
- class Program
- {
- static void Main(string[] args)
- {
- string str;
- char RepeatChar = ' '; //当前重复字符
- int RepeatCount = 1; //当前重复字符重复次数
- int repLength = 0; //出现几个连续重复字符
- Dictionary<char, int> dic = new Dictionary<char, int>();
- List<char> repChar = new List<char>();
- List<int> repCount =new List<int>();
- //输入字符串
- Console.Write("请输入字符串:");
- str = Console.ReadLine();
- //统计每个字符出现次数
- foreach (char a in str)
- {
- //统计每个字符出现次数
- if(dic.ContainsKey(a)) dic[a]++;
- else dic.Add(a,1);
- //统计连续重复
- if (RepeatChar != a)
- { //未连续重复
- RepeatChar = a;
- RepeatCount = 1;
- }
- else
- { //连续重复,添加和计数
- RepeatCount++;
- if (RepeatCount == 2)
- { //第二次重复,添加
- repLength++;
- repChar.Add(a);
- repCount.Add(2);
- }
- else
- { //多次重复
- repCount[repLength - 1] = RepeatCount;
- }
- }
- }
- //输出每个字符出现的次数
- foreach(KeyValuePair<char,int> key in dic)
- {
- Console.WriteLine("字符"+key.Key+"出现"+key.Value+"次。");
- }
- //输出连续重复的字符和重复次数
- for (int i = 0; i < repLength; i++)
- {
- Console.WriteLine("字符" + repChar[i] + "连续重复" + repCount[i] + "次。");
- }
- Console.ReadKey();
- }
- }
- }
复制代码 |