日期:2014-05-17  浏览次数:21060 次

C#--第七周实验--任务1--返回第二个参数在第一个参数中出现次数
/* (程序头部注释开始) 
 * 程序的版权和版本声明部分 
 * Copyright (c) 2011, 烟台大学计算机学院学生  
 * All rights reserved. 
 * 文件名称:返回第二个参数在第一个参数中出现次数
 * 作 者: 雷恒鑫  
 * 完成日期: 2012 年 10 月 11 日 
 * 版 本 号: V1.0  
 * 对任务及求解方法的描述部分 
 * 输入描述:编写一个名称为MyClass一个类,在该类中编写一个方法,名称为CountChar,返回值为整型,参数两个。
 * 输入描述:第一个参数可以是字符串、整数、单精度、双精度,第二个参数为字符,方法功能返回第二个参数在第一个参数中出现次数。如CountChar("6221982",'2')返回值为3。 
 * 问题描述: 
 * 程序输出: 
 * 程序头部的注释结束 
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace seven_week
{
    class Program
    {
        static void Main(string[] args)
        {
            MyClass c = new MyClass();
            Console.WriteLine("字符2在整数2345222中出现的个数为{0}", c.CountChar(2345222, '2'));
            Console.ReadKey();
        }
    }
    class MyClass
    {
        public int CountChar(int i, char c)
        {
            int s = 0, n = i, d = int.Parse(c.ToString());
            Boolean b = true;
            while (b == true)
            {
                if (i / 10 == 0)
                    b = false;
                i = i / 10;
                ++s;
            }
            int[] a = new int[s];
            i = n;
            for (int j = 0; j < s; ++j)
            {
                a[j] = i % 10;
                i = i / 10;
            }
            n = 0;
            for (int m = 0; m < s; ++m)
            {
                if (d == a[m])
                ++n;
            }
            return n;
        }
    }
}

运行结果: