C#l练习:①统计特定字符段出现的次数②统计所有字符出现的次数

①统计特定字符段出现的次数

代码实现:

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();
        }
    }
}

  

实现结果:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值