首页 > 其他 > 详细

面向对象基础(class0425)字符串与集合

时间:2014-07-05 21:20:03      阅读:362      评论:0      收藏:0      [点我收藏+]

常用类库

学习.net就是学习它的无数个类库怎么用,先看两个简单的

String 字符串,不可变特性。字符串可以看成字符数组

属性 Length

方法

IsNullOrEmpty() 静态方法

ToCharArray()

ToLower()

string不可变性

ToUpper()

Equals() 忽略大小写的比较

Join() 静态方法

Format () 静态方法

IndexOf()

LastIndexOf()

Substring()

Split()

Replace() Trim()  Contains()

字符串的处理练习1

课上练习1:接收用户输入的字符串,将其中的字符以与输入相反的顺序输出。"abc"→"cba"

课上练习2:接收用户输入的一句英文,将其中的单词以反序输出。 “I love you"→“uoy evol I"

课上练习3:”2012年12月21日”从日期字符串中把年月日分别取出来,打印到控制台

课上练习4:把csv文件中的联系人姓名和电话显示出来。简单模拟csv文件,csv文件就是使用,分割数据的文本

"","","15011111111";
"","","15011111112";
"","","15011111113";
"","","15011111114"

练习5:“192.168.10.5[port=21,type=ftp]”,这个字符串表示IP地址为192.168.10.5的服务器的21端口提供的是ftp服务,其中如果“,type=ftp”部分被省略,则默认为http服务。请用程序解析此字符串,然后打印出“IP地址为***的服务器的***端口提供的服务为***”

练习6:原字符串123-456--789----123-2,求123-456-789-123-2

练习7:从文件路径中提取出文件名(包含后缀) 。比如从c:/a/xxx.avi中提取出xxx.avi这个文件名出来

练习8:求员工工资文件中,员工的最高工资、最低工资、平均工资 张三,20 李四,21

string ss = "123-456--789----123-2";
            ss = ss.Replace("-", " ");
            string[] slist = ss.Split(new char[]{ }, StringSplitOptions.RemoveEmptyEntries);
            Console.WriteLine(string.Join("-",slist));

常用类库

StringBuilder高效的字符串操作

StringBuilder != String

StringBuilder sb = new StringBuilder();

sb.Append();

sb.ToString();

sb.Insert();

sb.Replace();

案例:使用程序拼html中的table

集合类

集合常用操作 添加、遍历、删除

命名空间System.Collections

ArrayList 可变长度数组,使用类似于数组

属性 Capacity Count

方法

Add() AddRange() Remove() RemoveAt() Clear() Contains() ToArray()

Hashtable 键值对的集合,类似于字典

案例:两个集合{ “a”,“b”,“c”,“d”,“e”}和{ “d”, “e”, “f”, “g”, “h” },把这两个集合去除重复项合并成一个

案例:随机生成10个1-100之间的数放到ArrayList中,要求这10个数不能重复,并且都是偶数

练习:有一个字符串是用空格分隔的一系列整数,写一个程序把其中的整数做如下重新排列打印出来:奇数显示在左侧、偶数显示在右侧。

比如‘2 7 8 3 22 9’显示成‘7 3 9 2 8 22’。

bubuko.com,布布扣
ArrayList al1 = new ArrayList() { "a","b","c","d","e"};
            ArrayList al2 = new ArrayList() { "d", "e", "f", "g", "h" };
            ArrayList al3 = new ArrayList();

            al3.AddRange(al1);
            foreach (string str in al2)
            {
                if (!al3.Contains(str)) 
                {
                    al3.Add(str);
                }
            }
            foreach (string str in al3)
            {
                Console.WriteLine(str);
            }

============================
    ArrayList al = new ArrayList();
            Random r = new Random();
            while (true) 
            {
                int n = r.Next(1, 101);
                if (n % 2 == 0)
                {
                    al.Add(n);
                }
                if (al.Count == 10)
                {
                    break;
                }
            }

=======================================
string s = "5 8 9 10 11 22 4 3";
            ArrayList al1 = new ArrayList();
            ArrayList al2 = new ArrayList();
            
            string[] arr = s.Split( );
            foreach (string item in arr)
            {
                int n = int.Parse(item);
                if (n % 2 != 0)
                {
                    al1.Add(n);
                }
                else 
                {
                    al2.Add(n);
                }
            }
View Code

(*)foreach

实现了IEnumerable(getEnumerator())、IEnumerable<T>的接口都可以使用foreach进行遍历。

我们可以自己写一个类使用foreach来遍历

案例:MyList 在这里可以发现foreach只允许读取数据,而不能修改数据 集合要支持foreach方式的遍历,必须实现IEnumerable接口(还要以某种方式返回实现了IEnumerator 的对象)

IEnumerator让foreach实现了查找下一项的能力

private int index;
        private string[] names;

        public MyList(int num) {
            index = -1;
            names = new string[num];
        }

        #region IEnumerator 成员

        //返回当前元素
        public object Current
        {
            get { 
                return names[index];
            }
        }
        //访问下一个元素,如果有返回true,否则返回false
        public bool MoveNext()
        {
            index ++;
            if(index >= names.Length){
                return false;
            }
            else{
                return true;
            }
        }
        //将索引置于第一个索引之前
        public void Reset()
        {
            index = -1;
        }

        #endregion
    
        #region IEnumerable 成员
        //返回枚举器,当前类实现了IEnumerator,要对当前对象进行遍历所以返回this
        public IEnumerator  GetEnumerator()
        {
            return (IEnumerator)this;
        }

        #endregion


从这两个接口的用词选择上,也可以看出其不同:IEnumerable是一个声明式的接口,声明实现该接口的class是“可枚举(enumerable)”的,但并没有说明如何实现枚举器(iterator);IEnumerator是一个实现式的接口,IEnumerator object就是一个iterator。

IEnumerable和IEnumerator通过IEnumerable的GetEnumerator()方法建立了连接,client可以通过IEnumerable的GetEnumerator()得到IEnumerator object,在这个意义上,将GetEnumerator()看作IEnumerator object的factory method也未尝不可。

泛型集合

书橱

命名空间System.Collections.Generic

List<T>类似于ArrayList

Dictionary<K,V>类似于Hashtable

T,K,V就像一把锁,锁住集合只能存某种特定的类型,这里的T,K,V也可以是其它字母

泛型集合可以进行foreach遍历,是因为实现了IEnumerable<T>

T/K/V是占位符,给数据类型占位 ,一旦替换为某种类型(可以是自己写的类),那么集合中只能存储这种类型的数据
这就是泛型集合

泛型集合

案例:把分拣奇偶数的程序用泛型实现。

练习:将int数组中的奇数放到一个新的int数组中返回 从一个整数的ArrayList、List<int>中取出最大数。别用max方法。

练习:汉英翻译

练习:编写一个函数进行日期转换,将输入的中文日期转换为阿拉伯数字日期,比如:二零一二年十二月月二十一日要转换为2012-12-21。

练习:计算字符串中每种字符出现的次数(面试题)。“Welcome to Chinaworld”,不区分大小写,打印“W2”“e 2”“o 3”……

string date = "二零一二年十二月二十一日";
            string[] arr = ziDian.Split( );
            foreach (string item in arr)
            {
                dic.Add(item.Substring(0, 1), item.Substring(1, 1));
            }
            Console.WriteLine(GetNum(date));
        }
        Dictionary<string, string> dic = new Dictionary<string, string>();
        string ziDian = "零0 一1 二2 三3 四4 五5 六6 七7 八8 九9";
        string GetNum(string date)
        {
            string newDate = "";
            for (int i = 0; i < date.Length; i++)
            {
                string num = date[i].ToString();
                if (num != "")
                {
                    if (dic.ContainsKey(num))
                    {
                        newDate += dic[num];
                    }
                    else
                    {
                        newDate += num;
     }
                }
                else
                {
                    if (i > 0 && i < date.Length)
                    {
                        string previousString = date.Substring(i - 1, 1);
                        string nextString = date.Substring(i + 1, 1);
                        if (dic.ContainsKey(previousString) && dic.ContainsKey(nextString))
                        {
                        }
                        else if (dic.ContainsKey(nextString))
                        {
                            newDate += "1";
                        }
                        else if (dic.ContainsKey(previousString))
                        {
                            newDate += "0";
                        }
                        else
                        {
                            newDate += "10";
  }
                    }
                }
            }
            return newDate.Replace("","-").Replace("","-").Replace("","");
        }
string s = "Welcome to Chinaworld";
            Dictionary<char, int> dict = new Dictionary<char, int>();//key为字符,value为出现的次数
            foreach (char ch in s.ToLower())
            {
                if (dict.ContainsKey(ch))//如果dict中含有这个字符就在出现次数上增加1
                {
                    //dict[ch]++;
                    dict[ch] = dict[ch] + 1;
                }
                else
                {
                    dict[ch] = 1;//如果不存在就初始化为1
                }
            }
            foreach (char ch in dict.Keys)
            {
                Console.WriteLine("{0}出现{1}次",ch,dict[ch]);
            }

 

 

面向对象基础(class0425)字符串与集合,布布扣,bubuko.com

面向对象基础(class0425)字符串与集合

原文:http://www.cnblogs.com/fanhongshuo/p/3826268.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!