C#統計字符出現的個數
題目描述
編寫一個實例方法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
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 num = 0;for (int i = 0; i < s.Length; i++){if (s[i] == c) num++;}return num;}}
}
?