压缩字符串的函数
需求:
给定指定长度的字符串(由字母构成),要求输出没有重复的字母串,重复的字母要求显示出现的次数。
实现:
Demo:
<span style="font-family:KaiTi_GB2312;font-size:18px;">/************************************************************************************ *机器名称:zlt *作者:周丽同 *小组:无 *修改时间:2016年8月19日 /************************************************************************************/ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace strl { class Program { static void Main(string[] args) { string str = "aaabbbcccdefg";//获取一个字符串 char[] chars = str.ToCharArray();//将字符串类型转为字符串数组类型 List<char> list1 = new List<char>();//实例化一个list for (int i = 0; i < chars.Length; i++)//遍历循环字符串数组中每一个字符 { int w = 0; for (int j=0; j < chars.Length; j++)//循环判断是否有重复的字符 { if (chars[i] == chars[j])//如果有类似的字符,计数加一 { w = w + 1; } } if(w>1)//判断有重复的字符 { int b = 0; for (int d = 0; d < list1.Count; d++) { if (chars[i] == list1[d]) { b = b + 1; } } if (b == 0) { Console.Write(w + "" + chars[i]); } list1.Add(chars[i]); } else//如果没有重复的字符 { Console.Write(chars[i]);//输出该字符 } } Console.ReadKey(); } } }</span>
效果: