[C#]上机实验:类的使用

要求:

1.编写一个名称为MyClass一个类,在该类中编写一个方法,名称为CountChar,返回值为整型,参数两个,第一个参数可以
是字符串、整数、单精度、双精度,第二个参数为字符,方法功能返回第二个参数在第一个参数中出现次数。
如CountChar("6221982",'2')返回值为3。

2.继续在该类中编写一下方法,名称为Reconvert,参数一个,但可以是字符串、整数、单精度、双精度,方法功能返回
参数的逆序。如Reconvert(6221982)返回值为2891226。

提示:将string转换为Char
      char[] c=strS.ToCharArray()

代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace EX4
{
    class Program
    {
        static void Main(string[] args)
        {
            MyClass mc=new MyClass();
            int num;
            num = mc.CountChar("6221982", '2');
            Console.WriteLine(num);
            string s;
            s = mc.Reconver("123456");
            Console.WriteLine(s);
            Console.ReadKey();
        }
    }

}


 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace EX4
{
    class MyClass
    {
        public int CountChar(string s, char a)
        {
            int count = 0;
            for (int i = 0; i < s.Length; i++)
            {
                if (s[i] == a)
                    count++;
            }
            return count;
        }

        public string Reconver(string s)
        {
            char[] c = s.ToCharArray();
            for (int i = 0; i < (c.Length - 1) / 2 + 1; i++)
            {
                char temp = c[i];
                c[i] = c[c.Length - 1 - i];
                c[c.Length - 1 - i] = temp;
            }
            string done = "";
            for (int i = 0; i < c.Length; i++)
            {
                done += c[i].ToString();//单个字符转化为string,不能写成c.ToString();

            }
            return done;
        }
    }
}


运行:

原文地址:https://www.cnblogs.com/sr1993/p/3697779.html