[C#]上机实验:类的使用
2014-03-21 16:01
218 查看
要求:
1.编写一个名称为MyClass一个类,在该类中编写一个方法,名称为CountChar,返回值为整型,参数两个,第一个参数可以
是字符串、整数、单精度、双精度,第二个参数为字符,方法功能返回第二个参数在第一个参数中出现次数。
如CountChar("6221982",'2')返回值为3。
2.继续在该类中编写一下方法,名称为Reconvert,参数一个,但可以是字符串、整数、单精度、双精度,方法功能返回
参数的逆序。如Reconvert(6221982)返回值为2891226。
提示:将string转换为Char
char[] c=strS.ToCharArray()
代码:
运行:
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; } } }
运行:
相关文章推荐
- [C#]上机实验:类的使用
- 第三周C#上机实验(一)有规律的求和
- 实验分析C#中三种计时器使用异同点
- C#强化系列文章三:实验分析C#中三种计时器使用异同点
- C#强化系列文章三:实验分析C#中三种计时器使用异同点
- 实验分析C#中三种计时器使用异同点
- C#强化系列文章三:实验分析C#中三种计时器使用异同点
- 『原创』+『参考』亲手实验:使用C#在PPC中播放声音
- 第二周C#上机实验(二)求取字母的ASCII值
- 实验分析C#中三种计时器使用异同点
- C#--第九周实验--任务3--定义一个静态成员方法,使用Random实现从一组数中随机抽取n个不重复的数。
- C#强化系列文章三:实验分析C#中三种计时器使用异同点
- c#上机实验之题目六
- C#上机实验之题目二
- C#上机实验之题目三
- C#强化系列文章三:实验分析C#中三种计时器使用异同点
- 实验分析C#中三种计时器使用异同点
- 实验心得:C#中当使用foreach对集合进行遍历时,不得改变集合的大小和元素的值
- Java第四周常用类与集合框架上机实验二学会Math类常用方法使用
- 第六章 使用C#开发数据库应用系统 上机练习1-4