C#基础加强题目和代码

1.交换两个变量的值 { class Program     {// 实现交换两变量的方法  static void Main(string[] args)         {             Console.WriteLine("请输入x的值");             string  x= Console.ReadLine();             Console.WriteLine("请输入y的值");             string y = Console.ReadLine();             Fuc(x, y);//调用交换变量的方法

        }         ///

        /// 实现交换两变量的方法         ///         ///         ///         static void Fuc(string a,string b)         {             Console.WriteLine("交换前x={0},y={1}",a,b);             string temp;             temp = a;             a = b;             b = temp;             Console.WriteLine("交换后x={0},y={1}",a,b);             Console.ReadKey();         }  } } 2.方法测试 (1)实现Max方法和Min方法 (2)求min与max间数的所有奇数的和 public int SumOdd(min,max); (3)寻找最胖福星 {200,120,190,1,110,34},求最大数。 class Program     {

        static void Main(string[] args)         {                        Sort(200,120,190,1,110,34);                         j=1                   j=2    200,120,190,1,11,34        120,190,1,11,34,200     120,200,190,1,11,34  i=0   120,190,1,11,34,200    120,190,200,1,11,34  i=1   120,1,190,11,34,200    120,190,1,200,11,34  i=2   120,1,11,190,34,200    120,190,1,11,200,34  i=3   120,1,11,34,190,200    120,190,1,11,34,200  i=4    5次交换,求出最大的。         }         public static void Sort(params int[] Array)         {             for (int j = 1; j < Array.Length; j++)             {                 for (int i = 0; i < Array.Length - 1; i++)                 {                     if (Array[i] > Array[i + 1])                     {                         int temp = Array[i];                         Array[i] = Array[i + 1];                         Array[i + 1] = temp;                     }                 }             }//用冒泡排序法进行排序,第一个为最小值,最后一个为最大值            int min = Array[0];            int max = Array[Array.Length-1];            int sum=0;            for (int i = min; i <= max; i++)            {                if (i % 2 == 0)                {                    continue;//假如是偶数直接进入下一次循环                }                sum += i;            }            Console.WriteLine("所有奇数和为{0}", sum);            Console.WriteLine("最大数为{0}", max);            Console.ReadKey();         }     } 3.写一个Person类,并设计Teacher类继承Person,Czteacher类继承Teacher类,用构造函数进行赋值。  class Person     {//创建一个person类为父类         string name;         int age;         char gender; //创建person构造函数         public Person(int age, char gender, string name)         {             this.name = name;             this.age = age;             this.gender = gender;         } //创建person无参构造函数,防止出错         public Person()         {         }

        public string Name         {             get { return name; }             set { name = value; }         }         public int Age         {             get { return age; }             set { age = value; }         }         public char Gender         {             get { return gender; }             set { gender = value; }         }         public void SayHello()         {             Console.WriteLine("大家好,我是{0},我今年{1}岁了,我是{2}生",                     Name, Age, Gender);         }     }       class Teacher:Person     {//创建一个Teacher类为子类,创建构造函数时,用base继承父类的属性         //base 关键字用于从派生类中访问基类的成员:

        //调用基类上已被其他方法重写的方法。

        //指定创建派生类实例时应调用的基类构造函数。         public Teacher(int age, char gender, string name, int teaNum)             : base(age, gender, name)             {             this.teaNum = teaNum;         }         //创建无参数重载构造方法,调用时不会出错。         public Teacher()         {         }

        int teaNum;         public int TeaNum         {             get { return teaNum; }             set { teaNum = value; }         }

        public void SayHello()         {             Console.WriteLine("大家好,我是{0},我今年{1}岁了,我是{2}生,我的工号是{3}",                     Name, Age, Gender, teaNum                 );         }     }   class Czteacher : Teacher     {//创建Czteacher类继承Teacher类,用base继承Teacher父类的属性         public Czteacher(int age, char gender, string name, int teaNum, string course)             : base(age, gender, name, teaNum)         {             this.course = course;         }         public Czteacher()         {         }         string course;         public string Course         {             get { return course; }             set { course = value; }         }         public void SayHello()         {             Console.WriteLine("大家好,我是{0},我今年{1}岁,我的性别是{2},我的工号是{3},在传智,我是{4}老师",                      Name, Age, Gender, TeaNum, Course);         }     }   class Program     {主方法         static void Main(string[] args)         {             Person p1=new Person(18,'女',"小燕");             p1.SayHello();             Teacher tea1 = new Teacher(33,'男',"张三",123456);             tea1.SayHello();             Czteacher tea2=new Czteacher(30,'男',"蒋坤",88888,".Net");             tea2.SayHello();             Console.ReadKey();         }     } 4.用WinForm作出窗口在屏幕上移动的效果 操作:在窗口上拖控件Time(组件),设置Time属性Enabled(启用)为ture,Interal(间距)为20,在事件里双击。  public partial class Form1 : Form     {         public Form1()         {             InitializeComponent();             StartPosition = FormStartPosition.Manual;//指定窗口初始位置,Manual是指由Location属性决定             Location = new Point(0, 0);//指定位置为坐标(0,0),这个坐标指的是窗体左上角坐标         }

        int seed1 = 2;         int seed2 = 2;//设定2个种子,决定X,Y坐标碰到边的时候进行转向。         private void timer1_Tick(object sender, EventArgs e)         {             int X = Location.X;             int Y = Location.Y;             if(X>=Screen.GetWorkingArea(new Point(0,0)).Width-Width||X<0)             {                 seed1=seed1*(-1);             }             else if (Y >= Screen.GetWorkingArea(new Point(0, 0)).Height - Height||Y<0)             {                 seed2 = seed2 * (-1);//Screen.GetWorkingArea是指屏幕的工作区域             }             Location=new Point(X+seed1,Y+seed2);             }

        private void Form1_Load(object sender, EventArgs e)         {

        }     } 5.带两个参数,完成这两个数字之间的整数输入(主要用于练习do....while,以便可以输入错误时可以重复输入)  class Program     {         static void Main(string[] args)         {             int a = new Program().InPutNum_3(23,65);             Console.WriteLine("你输入的整数是{0}", a);             Console.ReadKey();         }

          int InPutNum_3(int min,int max)           {               do               {                   try                   {                       Console.WriteLine("请输入一个大于{0}而且小于{1}的整数",min,max);                       int num = Convert.ToInt32(Console.ReadLine());                       if (num > min && num < max)                           return num;                       else                       {                           Console.WriteLine("输入错误");

                      }                   }                   catch                   {                       Console.WriteLine("输入错误");                   }               }               while (true);           }     }

6.创建一个结构体Person,并用构造方法赋初值 class Program     {//结构体的实例         struct person         {             private string name;

            public string Name             {                 get { return name; }                 set { name = value; }             }             private int age;

            public int Age             {                 get { return age; }                 set { age = value; }             }             private char sex;

            public char Sex             {                 get { return sex; }                 set { sex = value; }             }             //public const int num=10;             public void Student()             {                 Console.WriteLine("Hello World{0},{1},{2}",Name,Age,Sex);             }             public person(string name,int age,char sex)             {                 this.age = age;                 this.sex = sex;                 this.name = name;             }         }         static void Main(string[] args)         {

            //person p1;             //p1.name = "123";             //p1.sex = '1';             //p1.age = 12;             //p1.Student();             person p1 = new person("1", 12, '1');             p1.Student();             Console.ReadKey();

        }  } 7.里氏转换,定义父类person,子类chinese,japanese,American,Korean,实现里氏转换并输出,最后尝试用多态的方法进行输出 class Person     {//建立父类,里面有virtual的SayHello()的方法         string name;         public string Name         {             get { return name; }             set { name = value; }         }

        public virtual void SayHello()         {           }     }    class Chinese:Person     {//子类,有override的SayHello()的方法         public override void SayHello()         {             Console.WriteLine("我是{0}, 我是中国人,我来自中华人民共和国", Name);         }     }  class Japanese:Person     {//同上         public override void SayHello()         {             Console.WriteLine("什么什么死噶");         }     }    class American:Person     {//同上         public override void SayHello()         {             Console.WriteLine("Hello, I’m {0}", Name);         }     }    class Korean:Person     {//同上         public override void SayHello()         {             Console.WriteLine("啊你哟哈撒哟!!!");         }     }   class Program     {//主方法         static void Main(string[] args)         {              //1、子类直接赋值给父类(子类可以直接转化成父类)              //2、指向子类的父类,可以强制转化为对应的子类              // is运算符,用来判断父类对象可否转化为子类对象              //     对象 is 类型名              // 如果可以转换,就返回true,否则返回false

            Chinese c1 = new Chinese();             c1.Name = "张三";

            American a1 = new American();             a1.Name = "Jack";

            Japanese j1 = new Japanese();             j1.Name = "酒囊饭袋子";

            Korean k1 = new Korean();             k1.Name = "车载总";

            Person[] ps = { c1, a1, j1, k1 };

            // 类型决定了对象可以访问什么方法             //((Chinese)ps[0]).SayHello();             //((American)ps[1]).SayHello();             //((Japanese)ps[2]).SayHello();             //((Korean)ps[3]).SayHello();

            for (int i = 0; i < ps.Length; i++)             {                 #region 没有使用多态的时候                 //if( ps[i] is Chinese)                 //{                 //    ((Chinese)ps[0]).SayHello();                 //}                 //else if(ps[i] is American)                 //{                 //    ((American)ps[1]).SayHello();                 //}                 //else if(ps[i] is Japanese)                 //{                 //    ((Japanese)ps[2]).SayHello();                 //}                 //else                 //{                 //    ((Korean)ps[3]).SayHello();                 //}                 #endregion

                ps[i].SayHello();  //实现多态,在Person类中定义一个virtual(虚拟的)的SayHello()的方法,                                    //然后在每个子类中定义override(覆盖)的SayHello()的方法             }             Console.ReadKey();         }     } 8.定义USB为父类,iPhone,UDisk,FengShan为子类,通过多态实现方法; #region // 第一件事情,父类的方法只是为了提供一个“接口”(一个协议,目的是为了子类去实现)     //    在父类的方法前加上一个virtual,表示该方法会被子类所重写(替代)     // 第二件事情,在子类方法前加上override,表示重写了父类方法(替代)

    // 父类,国际ISO001020协议IEEE     class USB     {         public virtual void Insert()         {             Console.WriteLine("我是一个协议");         }     }

    // U盘生产商     class UDisk : USB     {         public override void Insert()         {             Console.WriteLine("传输数据");         }     }

    // iPhone     class iPhone : USB     {         public override void Insert()         {             Console.WriteLine("充电和传送数据");         }     }

    // 风扇     class FengShan : USB     {         public override void Insert()         {             Console.WriteLine("吹吹风");         }     }

    class Program     {         static void Main(string[] args)         {             // 直接将子类赋值给父类对象             // 由父类统一调用(方法相同)             // 由于真正的指向对象不同,那么可以实现统一调用,不同实现

            USB usb = new USB();  //实例化一个父类叫usb             usb = new iPhone();  //直接将子类的值赋值给父类             usb.Insert();    //由于父类的方法被隐藏,这里调用的其实是子类的方法

            usb = new UDisk();             usb.Insert();

            usb = new FengShan();             usb.Insert();

            ((FengShan)usb).Insert();

            Console.ReadKey();         }     } #endregion 9.多态的一个练习(难点)题目问输出是什么 namespace _13多态的一个练习 {     class A    {         public string Str = "A";         public void Show() { Console.WriteLine("Show A"); }     }     class B : A    {         public string Str = "B";                                    //B隐藏了父类A的Str属性         public virtual void Show() { Console.WriteLine("Show B"); }  //B隐藏了自己的方法     }     class C : B    {                                                //C继承了B的公开属性Str="B";         public override void Show() { Console.WriteLine("Show C"); }  //C重写了父类B的方法     }     class D : C    {         public string Str = "D";                         //D继承C,系统默认的隐藏了C的方法和属性         public void Show() { Console.WriteLine("Show D"); }     }

    class Program    {         static void Main(string[] args)        {             D d = new D();                         // 在这里,将子类D用里氏直接赋值给A,B,C             C c = d;                               //D本身有自己的方法和字段,直接输出    则   “D”,   "Show D"             B b = d;                               //C没有自己的Str,继承了父类B,而方法则为override 则输出  “B“,"Show C"             A a = d;                               //B有自己的Str,但是隐藏了自己的方法,由C进行重写 则为     "B","SHOW  C"             Console.WriteLine(d.Str);   // D       //A有自己的Str和方法,则为  "A",  "Show A"             Console.WriteLine(c.Str);   // B             Console.WriteLine(b.Str);   // B             Console.WriteLine(a.Str);   // A             Console.WriteLine("------------");             d.Show();   // D             c.Show();   // C             b.Show();   // C        ***             a.Show();   // A             Console.ReadLine();         }     }

} 10.多态练习,定义一个父类车类,然后定义子类,每个车都有自己的类型 namespace 多态练习02 {//含有父类和子类     class Vehicle     {         public virtual void Type()         {             Console.WriteLine("这是一辆车");         }     }     class Car : Vehicle     {         public override void Type()         {             Console.WriteLine("这是一辆轿车");         }     }     class Passengercar : Vehicle     {         public override void Type()         {             Console.WriteLine("这是一辆客车");         }     }     class Sportcar : Vehicle     {         public override void Type()         {             Console.WriteLine("这是一辆跑车");         }     }     class Truck : Vehicle     {         public override void Type()         {             Console.WriteLine("这是一辆卡车");         }     } } class Program     {//多态的运用         static void Main(string[] args)         {             //Vehicle v1 = new Vehicle();             //v1.Type();             //v1=new Car();             //v1.Type();             //v1=new Passengercar();             //v1.Type();             //v1=new Sportcar();             //v1.Type();             //v1 = new Truck();             //v1.Type();             //Console.ReadKey();             //Vehicle v1 = new Vehicle();             Vehicle[] vs = { new Car(), new Passengercar(), new Sportcar(), new Truck() };             //Car c1 = new Car();             //Passengercar p1=new Passengercar();             //Sportcar s1=new Sportcar();             //Truck t1 = new Truck();             //Vehicle[] vs = { c1, p1, s1, t1 };             for (int i = 0; i < vs.Length; i++)             {                 vs[i].Type();             }             Console.ReadKey();         }     } 11.计算器设计(多态,工厂模式,面向对象的理解)  class Factory     {//         public static Operation GetOpertation(string oper, double num1, double num2)         {             switch(oper)             {                 case "+": return new Add(num1, num2);                 case "-": return new Sub(num1, num2);                 case "*": return new Mul(num1, num2);                 case "/": return new Div(num1, num2);                 default: return null;             }         }     }  namespace 计算器练习 {     abstract class Operation     {         public abstract double Operate();         double num1;

        public double Num1         {             get { return num1; }             set { num1 = value; }         }         double num2;

        public double Num2         {             get { return num2; }             set { num2 = value; }         }     }     class Add : Operation     {         public Add(double num1, double num2)         {             this.Num1 = num1;             this.Num2 = num2;         }         public override double Operate()         {             return Num1 + Num2;         }     }     class Sub : Operation     {         public Sub(double num1, double num2)         {             this.Num1 = num1;             this.Num2 = num2;         }         public override double Operate()         {             return Num1 - Num2;         }     }     class Mul : Operation     {         public Mul(double num1, double num2)         {             this.Num1 = num1;             this.Num2 = num2;         }         public override double Operate()         {             return Num1 * Num2;         }     }     class Div : Operation     {         public Div(double num1, double num2)         {             this.Num1 = num1;             this.Num2 = num2;         }         public override double Operate()         {             if (Num2 == 0)             {                 Console.WriteLine("除数不能为0");             }                 return Num1 / Num2;         }     } }  class Program     {         static void Main(string[] args)         {             Console.WriteLine("请输入第一个数");             double num1 = Convert.ToDouble(Console.ReadLine());             Console.WriteLine("请输入第二个数");             double num2 = Convert.ToDouble(Console.ReadLine());             Console.WriteLine("请输入运算符");             string oper = Console.ReadLine();             Operation jisuan = Factory.GetOpertation(oper, num1, num2);//调用静态函数的方法,返回值经过里氏转换,             double res=0;                                              //完成构造方法的初始化赋值             if (jisuan != null)             {                 res = jisuan.Operate();                 Console.WriteLine("{0}{1}{2}={3}", num1, oper, num2, res);             }             else             {                 throw new Exception("输入异常");             }             Console.ReadKey();         }     } 12.接口与开车的例子 namespace 接口练习01 {     interface IDrivable     {         void driving();     }     class Person     {     }     class chinese1 : Person     {     }     class chinese2 : Person,IDrivable     {         public void driving()         {             Console.WriteLine("我会开车");    //定义一个chinese类,这类人会开车         }     }     class Program     {         static void Main(string[] args)         {             Random r = new Random();             Person[] p = new Person[100];             for (int i = 0; i < p.Length; i++)   //随即分配100个人,有会开车的,也有不会开车的             {                 if (r.Next() % 2 == 0)                 {                     p[i] = new chinese1();                 }                 else                 {                     p[i] = new chinese2();                 }             }             for (int i = 0; i < p.Length; i++)             {                 chinese2 driver = p[i] as chinese2;    //判断一个人是否属于chinese2                 if (driver != null)       //假如属于chinese2                 {                     Console.WriteLine(i);                     driver.driving();                 }                 else                 {                     Console.WriteLine(i);                     Console.WriteLine("我不会开车");                 }                             }             Console.ReadKey();         }     } } 13.namespace 接口练习_智能手机 {     class Program     {         static void Main(string[] args)         {             Random r = new Random();             phone[] ps = new phone[100];             for (int i = 0; i < ps.Length; i++)             {                 if (r.Next() % 2 == 0)                 {                     ps[i] = new phone();                 }                 else                 {                     ps[i] = new iPhone();                 }                             }

            //phone[] ps ={new phone(),             //                new iPhone(),             //                new phone(),             //                new iPhone(),             //                new phone (),             //                new iPhone()             //            };             for (int i = 0; i < ps.Length; i++)             {                 Console.WriteLine(i + 1);                 ps[i].Call();                 Iable p = ps[i] as Iable;                 if (p != null)                 {                     p.RunApplication();                 }                 Console.WriteLine();                             }             Console.ReadKey();         }     }     class phone     {         public void Call()         {             Console.WriteLine("打电话");         }     }     interface Iable     {         void RunApplication();     }     class iPhone : phone, Iable     {         public void RunApplication()         {             Console.WriteLine("我能运行程序");         }     }

} 14.模拟登陆,返回登陆是否成功(bool),如果登陆失败,     提示用户是用户名错误还是密码错误”admin”,“888888”   ref   ?  out  namespace out_ref {     class Program     {         static void Main(string[] args)         {             //long l = 1234567890123456012;             //double d = l;

            // 模拟登陆,返回登陆是否成功(bool),如果登陆失败,             // 提示用户是用户名错误还是密码错误”admin”,“888888”   ref   ?  out             string userName = "admin";             string password = "888888";             string msg;

            if (Login(userName, password, out msg))             {                 Console.WriteLine("登录成功");             }             else             {                 Console.WriteLine(msg);             }

            Console.ReadKey();         }

        static bool Login(string uid, string pwd, out string msg)         {             msg = null;             bool state = false;             if (uid == "admin" && pwd == "888888")             {                 state = true;             }             else if (uid == "admin")             {                 // Console.WriteLine("密码错误");                 msg = "密码错误";             }             else             {                 // Console.WriteLine("用户名不存在");                 msg = "用户名不存在";             }

            return state;         }     } } 15字符串练习题 <1>课上练习1:接收用户输入的字符串,将其中的字符以与输入相反的顺序输出。"abc"→"cba" namespace 练习01 {     class Program     {         static void Main(string[] args)         {             Console.WriteLine("请输入字符串");             string str = Console.ReadLine();             string str1=Exchange(str);             Console.WriteLine(str1);             Console.ReadKey();         }         public static string Exchange(string str1)         {             char[] c1 = str1.ToCharArray();             for (int i = 0; i < c1.Length; i++)             {                 c1[i] = str1[str1.Length - 1 - i];             }             str1 = new string(c1);             return str1;         }     } } <2>课上练习2:接收用户输入的一句英文,将其中的单词以反序输出。      “I love you"→“i evol uoy"

    class Program     {         static void Main(string[] args)         {             Console.WriteLine("请输入字符串");             string str=Console.ReadLine();             string [] str1 = str.Split(new char[] {' ','!'}, StringSplitOptions.RemoveEmptyEntries);             for (int i = 0; i < str1.Length; i++)             {                 str1[i] = Exchange(str1[i]);             }             string str2 = string.Join(" ", str1);             Console.WriteLine(str2);             Console.ReadKey();         }         public static string Exchange(string str1)         {             char[] c1 = str1.ToCharArray();             for (int i = 0; i < c1.Length; i++)             {                 c1[i] = str1[str1.Length - 1 - i];             }             str1 = new string(c1);             return str1;         }     } } <3>课上练习3:”2012年12月21日”从日期字符串中把年月日分别取出来,打印到控制台 方法1: class Program     {         static void Main(string[] args)         {             string str = "2012年12月21日";             string [] strs=str.Split(new char []{'年','月','日'},StringSplitOptions.RemoveEmptyEntries);             string s = string.Join("   ", strs);             Console.WriteLine(s);             Console.ReadKey();         }     } 方法2:namespace 练习03 {     class Program     {         static void Main(string[] args)         {             string str = "2012年12月21日";             int index1 = str.IndexOf("年");             int index2 = str.IndexOf("月");             int index3 = str.IndexOf("日");             string str1 = str.Substring(index1 - 4, 4);             string str2 = str.Substring(index2 - 2, 2);             string str3 = str.Substring(index3 - 2, 2);             string s = string.Format("{0}   {1}    {2}", str1, str2, str3);             Console.WriteLine(s);             Console.ReadKey();         }     } } <4> 课上练习4:把csv文件中的联系人姓名和电话显示出来。简单模拟csv文件,csv文件就是使用,分割数据的文本,输出:   姓名:张三  电话:15001111113 string[] lines = File.ReadAllLines(“1.csv”,Encoding.Default);//读取文件中的所有行,到数组中。 namespace 练习04 {     class Program     {         static void Main(string[] args)         {             string[] lines = File.ReadAllLines(@"F:\传智学习记录\上课视频资料\20120629第六天_字符串_集合\20120629第六天_字符串_Source\Source\电话.csv",Encoding.Default);             for (int i = 0; i < lines.Length; i++)             {                 string [] str=lines[i].Split(',');                 string res=string.Format("姓名:{0} \t  手机:{1}\t",str);                 Console.WriteLine(res);             }             Console.ReadKey();         }     } } 16集合练习题 <1>两个(ArrayList)集合{ “a”,“b”,“c”,“d”,“e”}和 { “d”, “e”, “f”, “g”, “h” },把这两个集合去除重复项合并成一个。 #region             string[] strs1 = { "a", "b", "c", "d", "e" };             string[] strs2 = { "d", "e", "f", "g", "h" };

            ArrayList list1 = new ArrayList();             ArrayList list2 = new ArrayList();

            list1.AddRange(strs1);             list2.AddRange(strs2);

            for (int i = 0; i < list2.Count; i++)             {                 if (!list1.Contains(list2[i]))                 {                     list1.Add(list2[i]);                 }             }                 Console.ReadKey(); #endregion <2>随机生成10个1-100之间的数放到ArrayList中,要求这10个数不能重复,并且都是偶数(添加10次,可能循环很多次。) namespace 练习题02 {     class Program     {         static void Main(string[] args)         {             ArrayList list = new ArrayList();             Random r = new Random();             while (list.Count < 10)             {                 int temp = r.Next(1, 101);                 if (!list.Contains(temp) && temp%2==0)                 {                     list.Add(temp);                 }             }         }     } } <3>有一个字符串是用空格分隔的一系列整数,写一个程序把其中的整数做如下重新排列打印出来:奇数显示在左侧、偶数显示在右侧。 比如”2 7 8 3 22 9 5 11”显示成”7 3 9 2 8 22….”。 namespace 练习03 {     class Program     {         static void Main(string[] args)         {             string str = "2 7 8 3 22 9 5 11";             string[] arr = str.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);  //对字符串进行分离处理             ArrayList listeven = new ArrayList();             ArrayList listodd = new ArrayList();             for (int i = 0; i < arr.Length; i++)             {                 int num = Convert.ToInt32(arr[i]);                 if (num % 2 == 0)                 {                     listeven.Add(arr[i]);   //把偶数放在偶数集合里                 }                 else                 {                     listodd.Add(arr[i]);    //把奇数放在奇数集合里                 }             }             listodd.AddRange(listeven);  //奇数在前将偶数集合添加到奇数集合里     string[] strs = (string[])listodd.ToArray(typeof(string));   //将集合listodd转化为string 数组         }     } } <4>输入一串字符串,输出每一个字符,并显示字符出现的次数 namespace 练习05 {     class Program     {         static void Main(string[] args)         {             Dictionary dir = new Dictionary();             string str = "我爱北京们都是好天安门,天安们都是好门天安门,天安们都是好门天安门,天安门上们都是好太阳升; 我们都是好孩子";             for (int i = 0; i < str.Length; i++)             {                 string temp = str[i].ToString();                 if (dir.ContainsKey(temp))                 {                     dir[temp]++;                 }                 else                 {                     dir.Add(temp, 1);                 }             }             StringBuilder sb = new StringBuilder();             foreach (KeyValuePair item in dir)             {                 sb.AppendFormat("{0} \t {1}\n",item.Key,item.Value);             }             Console.WriteLine(sb);             Console.ReadKey();                        }     } } (5) 山寨版评论提交 :定义Label1显示评论时出现的字和出现的次数,Label2为显示还可以输入多少字(上限140),textBox输入文本 Button提交,字数超出上限时不能提交。 namespace _06山寨微博提交客户端 {     public partial class Form1 : Form     {         public Form1()         {             InitializeComponent();         }

        Hashtable table = new Hashtable();

        private void textBox1_TextChanged(object sender, EventArgs e)         {             table.Clear();             // 1、检查个数             string str = txt.Text.Trim();             int num = str.Length;             // int numTotal = Convert.ToInt32(total.Text);             int numTotal = 140;             int dif = numTotal - num;             // 2、统计个数             for (int i = 0; i < str.Length; i++)             {                 // 看看这个字符串在集合中是否存在,如果存在个数加1,                 // 不存在,将其加进去,将个数初始化为1                 string current = str[i].ToString();                 if (table.ContainsKey(current))                 {                     // 存在                     int numTemp = Convert.ToInt32(table[current]);                     table[current] = numTemp + 1;                 }                 else                 {                     // 不存在                     table.Add(current, 1);                 }             }

            // 3、显示统计结果与总数             StringBuilder sb = new StringBuilder();             foreach (DictionaryEntry item in table)             {                 sb.AppendFormat("汉字{0}, 出现{1}次\r\n", item.Key, item.Value);             }             viewRes.Text = sb.ToString();

            // 4、考虑按钮是否可用             if (dif < 0)             {                 btnSender.Enabled = false;             }             else             {                 btnSender.Enabled = true;             }             total.Text = dif.ToString();         }

        private void Form1_Load(object sender, EventArgs e)         {

        }     } } (6)把分拣奇偶数的程序用泛型实现。List namespace 分拣奇偶数泛型实现 {     class Program     {         static void Main(string[] args)         {             string str = "2 7 8 3 22 9 5 11";             string [] strs = str.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);             List listeven = new List();             List listodd = new List();             for (int i = 0; i < strs.Length; i++)             {                 int temp = int.Parse(strs[i]);                 if (temp % 2 == 0)                 {                     listeven.Add(temp);                 }                 else                 {                     listodd.Add(temp);                 }             }             listodd.AddRange(listeven);             foreach (int item in listodd)             {                 Console.Write("{0} ",item);             }             Console.ReadKey();                   }             } } (7)将int数组中的奇数放到一个新的int数组中返回。 namespace int奇数分拣放到另一个int数组 {     class Program     {         static void Main(string[] args)         {             int [] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };             int [] arr1= SelectOdd(arr);  //定义一个数组接受返回的数组             foreach (int item in arr1)   //对数组进行遍历输出             {                 Console.WriteLine(item);             }             Console.ReadKey();         }         ///

        /// 输入一个数组作为参数,返回一个数组里面只有奇数         ///         ///         ///         public static int[] SelectOdd(int [] arr)         {             List listodd = new List();             for (int i = 0; i < arr.Length; i++)             {                 if (arr[i] % 2 == 1)                 {                     listodd.Add(arr[i]);                 }             }             int[] arrodd = (int[])listodd.ToArray();             return arrodd;         }     } } (8)从一个整数的List中取出最大数(找最大值)。别用max方法。 namespace 从一个整数中取出最大数 {     class Program     {         static void Main(string[] args)         {             //从一个整数的List中取出最大数(找最大值)。别用max方法。             int[] arr = { 53, 636, 734, 4, 5, 65, 6 };             List list = new List();             list.AddRange(arr);             int max = 0;             for (int i = 0; i < list.Count; i++)             {                 max = max > list[i] ? max : list[i];             }             Console.WriteLine(max);             Console.ReadKey();         }     } } (9)把123转换为:壹贰叁。Dictionary namespace 把123转换为_壹贰叁_ {     class Program     {         static void Main(string[] args)         {             //把123转换为:壹贰叁。Dictionary             Dictionary dir = new Dictionary();             dir.Add('1', '壹');             dir.Add('2', '贰');             dir.Add('3', '叁');             string str = "123";             StringBuilder sb = new StringBuilder();             for (int i = 0; i 拓展: 输入阿拉伯数字,对应输出大写中文。如输入324,则输出 叁贰肆 namespace _123456789 {     class Program     {         static void Main(string[] args)         {             Console.WriteLine("请输入1-9的阿拉伯数字");             string str1 =  "123456789" ;             string str2 = "壹贰叁肆伍陆柒捌玖";             Dictionary dir = new Dictionary();             for (int i = 0; i < str1.Length; i++)    {                 dir.Add(str1[i],str2[i]);        }             string strtemp = Console.ReadLine();             StringBuilder sb = new StringBuilder();             for (int i = 0; i < strtemp.Length; i++)             {                 if (dir.ContainsKey(strtemp[i]))                 {                     string temp =Convert.ToString( dir[strtemp[i]]);                     sb.AppendFormat("{0}", temp);                 }             }             Console.WriteLine(sb.ToString());             Console.ReadKey();         }     } } (10) 计算字符串中每种字符出现的次数(面试题)。 “Welcome to Chinaworld”,不区分大小写,打印“W2”“e 2”“o 3”…… 提示:Dictionary,char的很多静态方法。char.IsLetter() namespace 计算字符串中每种字符出现的次数 {     class Program     {         static void Main(string[] args)         {             string strtemp = "Welcome to Chinaworld";             string str = strtemp.ToLower();             Dictionary dir = new Dictionary();             for (int i = 0; i < str.Length; i++)             {                 if (char.IsLetter(str[i]))                 {                     if (dir.ContainsKey(str[i]))                     {                         dir[str[i]]++;                     }                     else                     {                         dir.Add(str[i], 1);                     }                 }

            }             StringBuilder sb = new StringBuilder();             foreach(KeyValuePair item in dir)             {                 sb.AppendFormat("{0}\t{1}\n", item.Key, item.Value);             }             Console.WriteLine(sb);             Console.ReadKey();         }     } } (11)简繁体转换 。Dictionary namespace 火星文翻译器 {     public partial class Form1 : Form     {         public Form1()         {             InitializeComponent();         }

        private void label1_Click(object sender, EventArgs e)         {

        }

        private void button1_Click(object sender, EventArgs e)         {               string Jian = "词库,见程序";               string HXW = "词库,见程序";               Dictionary dir=new Dictionary();               for (int i = 0; i < Jian.Length; i++)               {                   dir.Add(Jian[i], HXW[i]);               }               string txt1 = textBox1.Text;               StringBuilder sb = new StringBuilder();               StringBuilder sb1 = new StringBuilder();               for (int i = 0; i < txt1.Length; i++)               {                   if (dir.ContainsKey(txt1[i]))                   {                       string temp = Convert.ToString(dir[txt1[i]]);                       sb.AppendFormat("{0}", temp);                   }                   else                   {                       sb1.AppendFormat("{0}", txt1[i]);                   }               }               if (sb1.Length == 0)               {                   textBox2.Text = sb.ToString();               }               else               {                   MessageBox.Show(string.Format("{0}不能转换为繁体中文", sb1));               }                       }

        private void button2_Click(object sender, EventArgs e)         {             Clipboard.SetText(this.textBox2.Text);             MessageBox.Show("复制成功,请用Ctrl+V在外部粘贴");         }

        private void button3_Click(object sender, EventArgs e)         {             textBox1.Text = "";             textBox2.Text = "";         }

        private void Form1_Load(object sender, EventArgs e)         {

        }     } } (12)山寨版词典 namespace 山寨版词典 {     public partial class Form1 : Form     {         public Form1()         {             InitializeComponent();         }

        private void button1_Click(object sender, EventArgs e)         {             #region 词库             string str = @" 词库,看程序";             #endregion             string[] strs = str.Split(new string[] { "  ", "\r", "\n", "   ", "    " }, StringSplitOptions.RemoveEmptyEntries);             List listchinese = new List();             List listenglish = new List();             Dictionary dir = new Dictionary();             for (int i = 0; i < strs.Length; i++)             {                 if (i % 2 == 0)                 {                     listenglish.Add(strs[i]);                 }                 else                 {                     listchinese.Add(strs[i]);                 }             }             for (int i = 0; i < listenglish.Count; i++)             {                 if (!dir.ContainsKey(listenglish[i]))                 {                     dir.Add(listenglish[i], listchinese[i]);                 }             }             string strenglish = textBox1.Text;             if (dir.ContainsKey(strenglish))             {                 textBox2.Text = dir[strenglish];                 {                 }             }             else             {                 MessageBox.Show("此单词不存在");             }         }

        private void button3_Click(object sender, EventArgs e)         {             textBox1.Text = "";             textBox2.Text = "";         }

        private void button2_Click(object sender, EventArgs e)         {             Clipboard.SetText(this.textBox2.Text);             MessageBox.Show("复制成功,请用Ctrl+V在外部粘贴");         }

        private void Form1_Load(object sender, EventArgs e)         {

        }     } } 17.文件操作练习题 <1>文件复制 namespace 文件操作01 {     public partial class Form1 : Form     {         public Form1()         {             InitializeComponent();         }

        private void button1_Click(object sender, EventArgs e)         {             OpenFileDialog ofd = new OpenFileDialog();             if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)             {                 textBox1.Text = ofd.FileName;             }         }

        private void button2_Click(object sender, EventArgs e)         {             FolderBrowserDialog fbd = new FolderBrowserDialog();             if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)             {                 textBox3.Text = fbd.SelectedPath;             }         }

        private void button3_Click(object sender, EventArgs e)         {             if (string.IsNullOrWhiteSpace(textBox1.Text) ||                 string.IsNullOrWhiteSpace(textBox2.Text) ||                 string.IsNullOrWhiteSpace(textBox3.Text))             {                 return;             }             double Num=Convert.ToDouble(comboBox1.SelectedItem);             byte[] bs = new byte[(int)(Num * 1024 * 1024)];             FileStream read = new FileStream(textBox1.Text.Trim(), FileMode.Open, FileAccess.Read);             FileStream write = new FileStream(Path.Combine(textBox3.Text.Trim(), textBox2.Text).Trim(), FileMode.Create, FileAccess.Write);             using (read)             {                 using (write)                 {                     int count = 0;                     while((count=read.Read(bs,0,bs.Length))!=0)                     {                         write.Write(bs, 0, count);                     }                 }             }             MessageBox.Show("复制成功");

        }     } } <2>文件加密与解密 namespace 文件加密与解密 {     public partial class Form1 : Form     {         public Form1()         {             InitializeComponent();         }

        private void button1_Click(object sender, EventArgs e)         {             OpenFileDialog ofd = new OpenFileDialog();             if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)             {                 textBox1.Text = ofd.FileName;             }         }

        private void button4_Click(object sender, EventArgs e)         {             FolderBrowserDialog fbd = new FolderBrowserDialog();             if(fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)             {                 textBox3.Text = fbd.SelectedPath;             }

        }

        private void button2_Click(object sender, EventArgs e)         {             FileStream read = new FileStream(textBox1.Text.Trim(), FileMode.Open, FileAccess.Read);             FileStream write = new FileStream(Path.Combine(textBox3.Text.Trim(), textBox2.Text.Trim()), FileMode.Create, FileAccess.Write);             using (read)             {                 using (write)                 {                     int count = 0;                     byte[] bs = new byte[10000];                     while ((count = read.Read(bs, 0, bs.Length)) != 0)                     {                         for (int i = 0; i < count; i++)                         {                             bs[i] = (byte)(bs[i] - 1);                         }                         write.Write(bs, 0, count);                     }                 }             }             MessageBox.Show("加密成功");         }

        private void button3_Click(object sender, EventArgs e)         {             FileStream read = new FileStream(textBox1.Text.Trim(), FileMode.Open, FileAccess.Read);             FileStream write = new FileStream(Path.Combine(textBox3.Text.Trim(), textBox2.Text.Trim()), FileMode.Create, FileAccess.Write);             using (read)             {                 using (write)                 {                     int count = 0;                     byte[] bs = new byte[10000];                     while ((count = read.Read(bs, 0, bs.Length)) != 0)                     {                         for (int i = 0; i < count; i++)                         {                             bs[i] = (byte)(bs[i] + 1);                         }                         write.Write(bs, 0, count);                     }                 }             }             MessageBox.Show("解密成功");         }

        private void button5_Click(object sender, EventArgs e)         {             textBox1.Text = "";             textBox2.Text = "";             textBox3.Text = "";         }     } } <3>序列化 namespace 序列化 {     class Program     {         static void Main(string[] args)         {             List personlist = new List();             personlist.Add(new person("张三1",'男',18));             personlist.Add(new person("张三2", '男', 18));             personlist.Add(new person("张三3", '男', 18));             personlist.Add(new person("张三4", '男', 18));             personlist.Add(new person("张三5", '男', 18));             personlist.Add(new person("张三6", '男', 18));             FileStream write = new FileStream(@"C:\Users\Avraber\Desktop\新建文件夹\4.txt", FileMode.Create, FileAccess.Write);             using (write)             {                 BinaryFormatter bf = new BinaryFormatter();                 bf.Serialize(write,personlist);             }             FileStream read = new FileStream(@"C:\Users\Avraber\Desktop\新建文件夹\4.txt", FileMode.Open, FileAccess.Read);             using (read)             {                 BinaryFormatter bf = new BinaryFormatter();                 personlist= (List)bf.Deserialize(read);             }

        }     }     [Serializable]     class person     {         public person(string name, char gender, int age)         {             this.name = name;             this.age = age;             this.gender = gender;         }         string name;

        public string Name         {             get { return name; }             set { name = value; }         }         char gender;

        public char Gender         {             get { return gender; }             set { gender = value; }         }         int age;

        public int Age         {             get { return age; }             set { age = value; }         }     } } 18小说阅读器    解题思路 :   1.1  拖入控件splitContainer,这个控件中间有分割线。   1.2  左侧拖入Treeview控件,选择在父容器停靠。右侧拖入txtbox,多行模式,属性中dock选择fill.   1.3  双击窗口,进入Load事件,是初始化加载。创建路径Path,创建根节点“小说”,并返回类型为TreeNode的节点标记             TreeNode tn = TreeView1.Content.Nodes.Add("小说");             string path = Path.GetFullPath(@"txt");    GetTree(tn, path);   1.4  为了显示左边树形列表,需要创建递归方法      public void GetTree(TreeNode tn, string path)         {             string[] folder = Directory.GetDirectories(path);  //获得当前文件夹的子文件夹目录             string[] file = Directory.GetFiles(path,"*.txt");  //  过得当前目录得文件,删选出txt后缀名的文件

            for (int i = 0; i < folder.Length; i++)             {                 TreeNode tn1 = tn.Nodes.Add(Path.GetFileName(folder[i]));  //将获得的子文件夹目录加到节点上   注意前面的tn                 GetTree(tn1, folder[i]);             }             for (int i = 0; i < file.Length; i++)             {                 TreeNode tn2=tn.Nodes.Add(Path.GetFileName(file[i]));  //在节点文件夹上增加文件名,  注意前面的tn                 tn2.Tag = file[i];   //把文件信息给予Tag,Tag用于存储信息             }         }     1.5 选择TreeView的 afterselect事件,表示点击后触发的事件      private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)         {             if (e.Node.Tag != null) //点击节点后文件信息不为空             {                 textBox1.Text = File.ReadAllText(e.Node.Tag.ToString(), Encoding.Default);             }         }   1.6 textbox的属性中,scrollBars显示为Both,表示显示滚动条    19.查找工具  解题思路:  1.1 创建窗体,有3个Textbox,分别对应输入要查询的内容,选择要查询的文件夹,和输出结果。  1.2 选择文件夹用FolderBrowserDialog。     FolderBrowserDialog fbd = new FolderBrowserDialog();             if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)             {                 textBox3.Text = fbd.SelectedPath;             } 1.3 执行查询        List listres = new List();   //创建集合,用于存储搜索到的结果。         private void button1_Click(object sender, EventArgs e)         {       listres.Clear();              //清空集合里的内容,再次点击查询的时候不会留下上次的数据。             GetRes(textBox3.Text.Trim(), listres);             StringBuilder sb = new StringBuilder();             for (int i = 0; i < listres.Count; i++)             {                 sb.AppendFormat("{0}\r\n", listres[i]);             }             textBox2.Text = sb.ToString();         }         ///

        /// 递归方法,执行查询         ///         ///         ///         public void GetRes(string path, List list)         {             string[] folder = Directory.GetDirectories(path); //获得文件夹名称,folder中存储的为全路径             string[] files = Directory.GetFiles(path);    //获得文件名称,files中存储的为全路径             for (int i = 0; i < folder.Length; i++)             {                 GetRes(folder[i], list);                   //递归方法,查询出所有的文件夹             }             for (int i = 0; i < files.Length; i++)             {                 string temp = File.ReadAllText(files[i], Encoding.Default);  //查询文件,看是否包含所需的内容                 if (temp.Contains(textBox1.Text.Trim()))                     //有此内容的话则把完整路径添加如集合中                 {                      list.Add(files[i]);                 }             }         }

20.正则表达式练习题 <1>过滤禁用词汇 namespace 过滤禁用词汇 {     public partial class Form1 : Form     {         public Form1()         {             InitializeComponent();         }

        private void button1_Click(object sender, EventArgs e)         {             string str = textBox1.Text.Trim();             if (string.IsNullOrEmpty(str))             {                 return;             }             if (Regex.IsMatch(str, string.Join("|", listBan.ToArray())))             {                 MessageBox.Show("含有非法词汇,禁止提交");             }             else if (Regex.IsMatch(str, string.Join("|", listMod.ToArray())))             {                 MessageBox.Show("含有待审核词汇");             }             else             {                 MessageBox.Show("提交成功");             }         }         List listMod = new List();         List listBan = new List();         private void Form1_Load(object sender, EventArgs e)         {             string[] words = File.ReadAllLines("网站过滤词(部分).txt", Encoding.Default);             for (int i = 0; i < words.Length; i++)             {                 string[] temp = words[i].Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);                 if (temp[1] == "{MOD}")                 {                     char[] chs = temp[0].ToCharArray();                     StringBuilder sb = new StringBuilder();                     for (int j = 0; j < chs.Length; j++)                     {                         sb.Append(chs[j] + ".{0,4}");                     }                     listMod.Add(sb.ToString());                 }                 else if (temp[1] == "{BANNED}")                 {                     char[] chs = temp[0].ToCharArray();                     temp[0] = string.Join(".{0,4}", chs);                     listBan.Add(temp[0]);                 }             }         }     } } <2>解析IP namespace 解析IP {     class Program     {         static void Main(string[] args)         {             string str = "192.168.1.100[port=8080,type=ftp]";             Match m1 = Regex.Match(str, @"\d{0,3}(\.\d{0,3}){3}");             if (m1.Success)             {                 Console.WriteLine("IP地址为{0}", m1.Value);             }             Match m2 = Regex.Match(str, @"port=(\d+)");             if (m2.Success)             {                 Console.WriteLine("端口为{0}", m2.Groups[1].Value);             }             Match m3 = Regex.Match(str, @"type=(\w+)");             if (m3.Success)             {                 Console.WriteLine("类型为{0}", m3.Groups[1].Value);             }             Console.ReadKey();         }     } } <3>判断URL是否合法 namespace 判断URL是否合法 {     class Program     {         static void Main(string[] args)         {             string str = "http://www.test.com/a.htm";             Match m = Regex.Match(str, @"[a-zA-z]+://[^\s]*");             if (m.Success)             {                 Console.WriteLine("正确");             }             else             {                 Console.WriteLine("错误");             }             Console.ReadKey();         }     } } <4>判断日期是否合法 namespace 判断日期是否合法 {     class Program     {         static void Main(string[] args)         {             string str="2012-12-21";             Match m = Regex.Match(str, @"^\d{4}\-((0[1-9])|(1[0-2]))-((0[1-9])|(1[0-9])|(2[0-9])|(3[0-1]))$");             if (m.Success)             {                 Console.WriteLine("合法");             }             else             {                 Console.WriteLine("非法");             }             Console.ReadKey();

        }     } } <5>匹配根目录下的文件夹 namespace 匹配根目录下的文件夹 {     class Program     {         static void Main(string[] args)         {             string str = @"C:\Windows\System32\myCmd.dll";             MatchCollection ms = Regex.Matches(str, @"(\w+)\\");             foreach (Match m in ms)             {                 if (m.Success)                 {                     Console.WriteLine("文件夹名字是{0}\t\r\n", m.Groups[1].Value);                 }             }             Match m1 = Regex.Match(str, @".+\\(.+)");             if (m1.Success)             {                 Console.WriteLine("文件名是{0}", m1.Groups[1].Value);             }             Console.ReadKey();         }     } } <6>匹配国内电话号码 namespace 匹配国内电话号码 {     class Program     {         static void Main(string[] args)         {             while (true)             {                 Console.WriteLine("请输入号码,区号请用-区分");                 string str = Console.ReadLine();                 Match m1 = Regex.Match(str, @"^\d{3}-\d{8}$|^\d{4}-\d{7}$");                 Match m2 = Regex.Match(str, @"^\d{11}$");                 Match m3 = Regex.Match(str, @"^\d{5}$");                 if (m1.Success)                 {                     Console.WriteLine("你输入的是电话号码{0}", m1.Value);                 }                 else if (m2.Success)                 {                     Console.WriteLine("你输入的是手机号码{0}", m2.Value);                 }                 else if (m3.Success)                 {                     Console.WriteLine("你输入的是服务号码{0}", m3.Value);                 }                 else                 {                     Console.WriteLine("输入错误");                 }                 Console.WriteLine();             }            Console.ReadKey();         }     } } <7>匹配身份证号码 namespace 匹配身份证号码 {     class Program     {         static void Main(string[] args)         {             while (true)             {                 Console.WriteLine("请输入号码");                 string ID= Console.ReadLine();                 Match m1 = Regex.Match(ID, @"^\d{15}$");                 Match m2=Regex.Match(ID,@"^\d{14}([0-9X]{4})$");                 if (m1.Success)                 {                     Console.WriteLine("输入正确{0}",m1.Value);                 }                 else if (m2.Success)                 {                     Console.WriteLine("输入正确{0}", m2.Value);                 }                 else                 {                     Console.WriteLine("输入错误!");                 }                 Console.WriteLine();             }             Console.ReadKey();         }     } } <8>提取数字 namespace 提取数字 {     class Program     {         static void Main(string[] args)         {             string str = "hello,2010年10月10日是个好日子。恩,9494.吼吼!886.";             MatchCollection ms = Regex.Matches(str, @"\d+");             foreach (Match m in ms)             {                 if (m.Success)                 {                     Console.WriteLine("{0}\t\r\n", m.Value);                 }             }             Console.ReadKey();         }     } } <9>提取邮箱信息 namespace 提取邮箱 {     public partial class Form1 : Form     {         public Form1()         {             InitializeComponent();         }

        private void Form1_Load(object sender, EventArgs e)         {         }

        private void button1_Click(object sender, EventArgs e)         {             // 1、下载HTML代码             WebClient wc = new WebClient();             wc.Encoding = Encoding.UTF8;             string html = wc.DownloadString(textBox1.Text.Trim());             // 2、正则提取             string regex = @"([0-9a-zA-Z\._-]+)@([0-9a-zA-Z-_]+(\.[0-9a-zA-Z-_]+)+)";             MatchCollection ms = Regex.Matches(html, regex);             StringBuilder sb = new StringBuilder();             foreach (Match m in ms)             {                 if (m.Success)                 {                     sb.AppendFormat("{0}\t\r\n", m.Value);                 }             }             textBox2.Text = sb.ToString();         }

        private void button2_Click(object sender, EventArgs e)         {             SaveFileDialog sfd = new SaveFileDialog();             if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)             {                 sfd.OpenFile();             }         }     } } <10>.用户登录信息验证 namespace 用户登录 {     public partial class Form1 : Form     {         public Form1()         {             InitializeComponent();         }         bool b1, b2, b3, b4;         private void button1_Click(object sender, EventArgs e)         {             if (b1 && b2 && b3 && b4)             {                 MessageBox.Show("注册成功");             }             else             {                 MessageBox.Show("请完善信息");             }                   }

        private void textBox1_Leave(object sender, EventArgs e)         {             if(string.IsNullOrEmpty(textBox1.Text.Trim()))             {                 return;             }             b1 = Regex.IsMatch(textBox1.Text.Trim(), @"^\w{5,10}$");             if (b1)             {                 labelUid.ForeColor = Color.Green;                 labelUid.Text = "恭喜,格式正确!";             }             else             {                 labelUid.ForeColor = Color.Red;                 labelUid.Text = "输入错误,请检查用户名长度和格式";             }         }

        private void textBox3_Leave(object sender, EventArgs e)         {             if (string.IsNullOrEmpty(textBox3.Text.Trim()))             {                 return;             }             b2 = Regex.IsMatch(textBox3.Text.Trim(), @"^\d{6}$");             if (b2)             {                 labelpas.ForeColor = Color.Green;                 labelpas.Text = "恭喜,密码输入正确!";             }             else             {                 labelpas.ForeColor = Color.Red;                 labelpas.Text = "输入错误,请检查密码长度和格式";             }         }

        private void textBox2_Leave(object sender, EventArgs e)         {             if (string.IsNullOrEmpty(textBox2.Text.Trim()))             {                 return;             }             b3=textBox2.Text.Trim()==textBox3.Text.Trim();             if (b3)             {                 labelpas2.ForeColor = Color.Green;                 labelpas2.Text = "恭喜,密码验证正确!";             }             else             {                 labelpas2.ForeColor = Color.Red;                 labelpas2.Text = "输入错误,请检查密码";             }         }

        private void textBox4_Leave(object sender, EventArgs e)         {             if (string.IsNullOrEmpty(textBox4.Text.Trim()))             {                 return;             }             b4=Regex.IsMatch(textBox4.Text.Trim(), @"^[0-9a-zA-Z\.-_]+@[0-9a-zA-Z\-_]+(\.[0-9a-zA-Z\-_]+)+$");             if (b4)             {                 labelmail.ForeColor = Color.Green;                 labelmail.Text = "恭喜,邮箱输入正确!";             }             else             {                 labelmail.ForeColor = Color.Red;                 labelmail.Text = "输入错误,请检查邮箱格式";             }         }

        private void textBox4_TextChanged(object sender, EventArgs e)         {

        }

        private void Form1_Load(object sender, EventArgs e)         {

        }     } } 21委托 <1>委托的基本运用 namespace 委托 {     public delegate void funcDelegate();     class Program     {         static void Main(string[] args)         {             Wo w = new Wo();             w.func();             funcDelegate laozhai;             laozhai = w.func;             laozhai();             Console.ReadKey();         }     }     class Wo     {         public void func()         {             Console.WriteLine("旁边是213");         }     } <2>委托变量的传值处理 namespace 委托变量的传值处理 {     public delegate void FucDelegate();     class Program     {         static void Main(string[] args)         {             while(true)             {                 FucDelegate Myfunc=null;                 Console.WriteLine("请输入Y来确定方法的执行");                 string m = Console.ReadLine();                 if(m=="Y")                 {                     Myfunc = Say;                 }                 Fuc(Myfunc);                 Console.WriteLine();                 Console.ReadKey();                            }         }         public static void Fuc(FucDelegate function)         {             if (function != null)             {                 function();             }         }         public static void Say()         {             Console.WriteLine("我出来啦");         }     } } <3>抓取图片 namespace 抓取图片 {     public partial class Form1 : Form     {         public Form1()         {             InitializeComponent();         }

        private void button1_Click(object sender, EventArgs e)         {             WebClient wc = new WebClient();             string html = wc.DownloadString(textBox1.Text.Trim());             // 2、正则提取             List list = new List();             MatchCollection ms = Regex.Matches(html, @"<\s?img[^>]+src=""([^""]+)""");             foreach (Match m in ms)             {                 if (m.Success)                 {                     list.Add(m.Groups[1].Value.Trim());                 }             }             // 与网页地址拼接得到图片的具体地址             string url = textBox1.Text.Trim();             for (int i = 0; i < list.Count; i++)             {                 string temp = list[i];                 temp = url + "/" + temp;                 list[i] = temp;             }

            // 下载             string dir = textBox2.Text.Trim();   //这里http://192.168.1.142:8090要把最后的斜杠去掉。             if(!Directory.Exists(dir))             {                 Directory.CreateDirectory(dir);             }             for (int i = 0; i < list.Count; i++)    {                 string name = Regex.Match(list[i], @".+/(.+)").Groups[1].Value;                 wc.DownloadFile(list[i], Path.Combine(dir, name));    }             MessageBox.Show("提取成功");                     }

        private void Form1_Load(object sender, EventArgs e)         {

        }

        private void button2_Click(object sender, EventArgs e)         {             FolderBrowserDialog fbd = new FolderBrowserDialog();             if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)             {                 textBox2.Text = fbd.SelectedPath;             }         }     } } <4>抓取招聘信息 namespace 抓取招聘信息 {     public partial class Form1 : Form     {         public Form1()         {             InitializeComponent();         }

        private void button1_Click(object sender, EventArgs e)         {             // 1、下载HTML代码             WebClient wc = new WebClient();             wc.Encoding = Encoding.Default;             string html = wc.DownloadString(textBox1.Text.Trim());             // 2、正则提取             string regex = @"class=""jobname"" target=""_blank"">(.+)";             MatchCollection ms = Regex.Matches(html, regex);             StringBuilder sb = new StringBuilder();             foreach (Match m in ms)             {                 if (m.Success)                 {                     sb.AppendFormat("{0}\t\r\n", m.Groups[1].Value);                 }             }             textBox2.Text = sb.ToString();         }

        private void Form1_Load(object sender, EventArgs e)         {

        }     } } <5>自定义排序Form namespace 自定义排序Form {     public delegate bool CompairDelegate(string s1, string s2);     public partial class Form1 : Form     {         public Form1()         {             InitializeComponent();         }         List list = new List();         StringBuilder sb = new StringBuilder();         CompairDelegate MyFunc;         Random r1 = new Random();         Random r2 = new Random();         public string[] nums;         public int count;         string str;         private void button4_Click(object sender, EventArgs e)         {             sb.Clear();             count = r1.Next(5, 10);             for (int j = 0; j < count; j++)             {                 int count1 = r1.Next(5, 10);                 for (int i = 0; i < count1; i++)                 {                     char temp1 = Convert.ToChar(r2.Next(48, 57));                     char temp2 = Convert.ToChar(r2.Next(65, 90));                     char temp3 = Convert.ToChar(r2.Next(97, 122));                     char[] temps = { temp1, temp2, temp3 };                     sb.Append(temps);                 }                 list.Add(sb.ToString());                 sb.Clear();             }             nums = list.ToArray();             for (int i = 0; i < list.Count; i++)             {                 sb.AppendFormat("{0}\t\r\n", list[i]);             }             textBox1.Text = sb.ToString();         }         private void button1_Click(object sender, EventArgs e)         {             str = "1";             Myswitch(str);         }         private void button2_Click(object sender, EventArgs e)         {             str = "2";             Myswitch(str);         }         private void Form1_Load(object sender, EventArgs e)         {         }         public void Myswitch(string str)         {             switch (str)             {                 case "1": MyFunc = new CompairDelegate(MyCompair1); break;                 case "2": MyFunc = new CompairDelegate(MyCompair2); break;                 case "3": MyFunc = MyCompair3; break;                 default: MyFunc = MyCompair1; break;             }

            Compair(nums, MyFunc);             sb.Clear();

            for (int i = 0; i < list.Count; i++)             {                 sb.AppendFormat("{0}\t\r\n", nums[i]);             }             textBox1.Text = sb.ToString();         }                     public static void Compair(string[] nums, CompairDelegate Func)         {             for (int i = 0; i < nums.Length - 1; i++)             {                 for (int j = 0; j < nums.Length - i - 1; j++)                 {                     // 传入什么样的方法,就做什么样的比较                     if (Func(nums[j], nums[j + 1]))                     {                         string temp = nums[j];                         nums[j] = nums[j + 1];                         nums[j + 1] = temp;                     }                 }             }         }         public static bool MyCompair1(string s1, string s2)         {             return string.Compare(s1, s2) > 0;         }         public static bool MyCompair2(string s1, string s2)         {             return s1.Length > s2.Length;         }         public static bool MyCompair3(string s1, string s2)         {             // 提取其中的数字,如果没有数字,默认为0             // 然后比较数字             // s1 > s2 则返回true             int num1 = 0;             int num2 = 0;             Match m1 = Regex.Match(s1, @"-?\d+");             Match m2 = Regex.Match(s2, @"-?\d+");             if (m1.Success)             {                 num1 = Convert.ToInt32(m1.Value);             }             if (m2.Success)             {                 num2 = Convert.ToInt32(m2.Value);             }             return num1 > num2 ? true : false;         }

        private void button3_Click(object sender, EventArgs e)         {             str = "3";             Myswitch(str);         }     } } <6>组替换 namespace 组替换 {     class Program     {         static void Main(string[] args)         {             //将一段文本中的MM/DD/YYYY格式的日期转换为YYYY-MM-DD格式 ,比如“我的生日是05/21/2010耶”转换为“我的生日是2010-05-21耶”             string str1 = "我的生日是05/21/2010耶";             str1 = Regex.Replace(str1, @"(\d+)/(\d+)/(\d+)", "$3-$1-$2");             Console.WriteLine(str1);

            // 练习2:给一段文本中匹配到的url添加超链接             //比如把http://www.test.com替换为 http://www.test.com。             string str2 = " http://www.test.com ";             str2 = Regex.Replace(str2, @" (.+?) ",@" $1");             Console.WriteLine(str2);             Console.ReadKey();         }     } } <7>委托链的应用 namespace 委托链 {     public delegate void FucDelegate();     class Program     {         static void Main(string[] args)         {             MyControl m = new MyControl();             m.Close();             Console.ReadKey();         }     }     class JIQI1     {         public void Close()         {             Console.WriteLine("机器1关闭");         }     }     class JIQI2     {         public void Close()         {             Console.WriteLine("机器2关闭");         }     }     class JIQI3     {         public void Close()         {             Console.WriteLine("机器3关闭");         }     }     class JIQI4     {         public void Close()         {             Console.WriteLine("机器4关闭");         }     }     class MyControl     {         JIQI1 j1 = new JIQI1();         JIQI2 j2 = new JIQI2();         JIQI3 j3 = new JIQI3();         JIQI4 j4 = new JIQI4();         public FucDelegate Func;         public MyControl()   //在委托链上增加这些方法来控制。         {             Func = j1.Close;             Func += j2.Close;             Func += j3.Close;             Func += j4.Close;                  }         public void Close()         {             Func();       //实现委托         }     } } 22XML <1>LinktoXML namespace LinktoXML {     class Program     {         static void Main(string[] args)         {             //1.创建一个XML文档                XDocument XDoc = new XDocument();             //2.添加根节点  XElement 元素             XElement XRoot = new XElement("Root");   //需要写入根节点名             XDoc.Add(XRoot);             //创建一个省加入到Root中             XElement xProvince = new XElement("Province");             XRoot.Add(xProvince);             //创建省名,位置,省会加入到xProvince中             XElement xName = new XElement("Name");             XElement xLocation = new XElement("Location");             XElement xPcaptial = new XElement("Captial");             xName.Value = "江苏";             xLocation.Value = "东部";             xPcaptial.Value = "南京";             xProvince.Add(xName, xLocation, xPcaptial);             //为 xProvince添加属性             XAttribute xNum = new XAttribute("ID", "001");             xProvince.Add(xNum);             //保存XML文档             XDoc.Save(@"F:\myxml.xml");         }     } } <2>XML序列化 namespace XML序列化 {     class Program     {         static void Main(string[] args)         {             List perList = new List()             {                 new Person(){ Name="董超 ",Age=19, Gender='男'},                 new Person(){ Name="周杰伦",Age=30, Gender='男'},                 new Person(){ Name="蔡依林",Age=28, Gender='女'}             };             using (FileStream file =                 new FileStream("序列化xml.xml", FileMode.Create, FileAccess.Write))             {                 XmlSerializer ser = new XmlSerializer(typeof(List));                 ser.Serialize(file, perList);             }         }     }     [Serializable]     public class Person     {         string name;

        public string Name         {             get { return name; }             set { name = value; }         }         int age;

        public int Age         {             get { return age; }             set { age = value; }         }         char gender;

        public char Gender         {             get { return gender; }             set { gender = value; }         }         public Person()         {         }     } } 23

 

 

 

转载于:https://www.cnblogs.com/zxp19880910/archive/2012/09/06/2674282.html

你可能感兴趣的:(C#基础加强题目和代码)