①统计特定字符段出现的次数
代码实现:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { int sum = 0; string s1 = "患者:“大夫,我咳嗽得很重。” 大夫:“你多大年记?” 患者:“七十五岁。” 大夫:“二十岁咳嗽吗”患者:“不咳嗽。” 大夫:“四十岁时咳嗽吗?” 患者:“也不咳嗽。” 大夫:“那现在不咳嗽,还要等到什么时咳嗽?”"; char[] a = s1.ToCharArray(); for (int i = 0; i < a.Length - 1; i++) { if (a[i] == '咳' && a[i + 1] == '嗽') sum++; } Console.WriteLine("咳嗽字符串出现的次数为{0}", sum); Console.ReadKey(); } } }
输出结果:
②统计所有字符出现的次数
代码实现:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { string s1 = "患者:“大夫,我咳嗽得很重。” 大夫:“你多大年记?” 患者:“七十五岁。” 大夫:“二十岁咳嗽吗”患者:“不咳嗽。” 大夫:“四十岁时咳嗽吗?” 患者:“也不咳嗽。” 大夫:“那现在不咳嗽,还要等到什么时咳嗽?”"; char[] a = s1.ToCharArray(); int[] a1=new int [a.Length];//计数数组 int[] a2=new int [a.Length];//标记数组 char c4; for (int i = 0; i < a.Length; i++) { a1[i] = 0; a2[i] = 0; } for (int i = 0; i < a.Length; i++) { if (a2[i] == 0)//为遍历过就将他查询 { c4 = a[i];//获取值 for (int j = i; j < a.Length; j++) { if (a[j] == c4 && a2[j] == 0)//查询他的值之后的 { a1[i]++;//统计与他相同的值 a2[j] = 1;//标记已经被计算过 } } } } for (int i = 0; i < a.Length; i++) { if (a1[i] > 1) { Console.Write("{0} ", a[i]); Console.Write("{0} ", a1[i]); } } Console.ReadKey(); } } }
实现结果: