站点图标 陌路寒暄

C#统计字符出现的个数

C#统计字符出现的个数

时间: 1ms        内存:128M

描述:

编写一个实例方法getCountChar方法。该方法参数有两个,第一个参数可以是字符串s,第二个参数为字符c,方法返回值为第二个参数在第一个参数中出现次数。例如,CountChar("6221982",'2')返回值为3。
部分程序代码已经给出。
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 str = Console.ReadLine();     
            char ch = (char) Console.Read();
            Program pro = new Program();
            Console.WriteLine(pro.getCountChar(str,ch));

            //Console.ReadKey();
        }
        public int getCountChar(String s,char c){
        //

        在此处填写代码

        //
        }
    }
}

提交时,请提交整个题目!!!

输入:

一个字符串s,一个字符c

输出:

该字符c在字符串s中的出现次数

示例输入:

6221982
2

示例输出:

3

提示:

参考答案(内存最优[4332]):

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 str = Console.ReadLine();     
            char ch = (char) Console.Read();
            Program pro = new Program();
                Console.WriteLine(pro.getCountChar(str,ch));
 
            //Console.ReadKey();
        }
        public int getCountChar(String s,char c){
        int admin=0;
        foreach (char myChar in s)
        {
                if(c==myChar){
                 admin++;
                }
        }
            return admin; 
        }
    }
}

参考答案(时间最优[25]):

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 str = Console.ReadLine();     
            char ch = (char) Console.Read();
            Program pro = new Program();
                Console.WriteLine(pro.getCountChar(str,ch));
 
            //Console.ReadKey();
        }
        public int getCountChar(String s,char c){
        int admin=0;
        foreach (char myChar in s)
        {
                if(c==myChar){
                 admin++;
                }
        }
            return admin; 
        }
    }
}

题目和答案均来自于互联网,仅供参考,如有问题请联系管理员修改或删除。

退出移动版