/* (程序头部注释开始)
* 程序的版权和版本声明部分
* Copyright (c) 2011, 烟台大学计算机学院学生
* All rights reserved.
* 文件名称: 《编写一个方法,返回第二个参数在第一个参数中出现次数——C#第五周》
* 作 者: 刘江波
* 完成日期: 2012 年 10 月 3 日
* 版 本 号: v1.1
* 对任务及求解方法的描述部分
* 问题描述:
编写一个名称为MyClass一个类,在该类中编写一个方法,名称为CountChar,返回值为整型,参数两个,第一个参数可以是字符串、整数、单精度、双精度,第二个参数为字符,方法功能返回第二个参数在第一个参数中出现次数。如CountChar("6221982",'2')返回值为3。
* 程序头部的注释结束
*/
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class MyClass { //1.编写一个名称为MyClass一个类,在该类中编写一个方法,名称为CountChar,返回值为整型,参数两个, //第一个参数可以是字符串、整数、单精度、双精度,第二个参数为字符,方法功能返回第二个参数在第一个参数中出现次数。 //如CountChar("6221982",'2')返回值为3。 int CountChar(string st1, char c) { int n = 0; for (int i = 0; i < st1.Length; i++) { if (st1[i].Equals(c)) { n++; } } return n; } static void Main(string[] args) { MyClass m1 = new MyClass(); Console.WriteLine("请输入第一个参数(第一个参数可以是字符串、整数、单精度、双精度)"); string st1 = Console.ReadLine(); Console.WriteLine("请输入第二个参数(第二个参数为字符)"); string st2 = Console.ReadLine(); char c = char.Parse(st2); int n = m1.CountChar(st1, c); Console.WriteLine("第二个参数在第一个参数中出现{0}次", n); Console.ReadKey(); } } }