拆分字符串

拆分一个字符串,获取每一组的key与value。

如字符串:

"qq=adf;f=qewr98;eer=d9adf;t=ad34;f=qewrqr;u=adf43;gggg=2344"

 

按照面向对象理念来解决,创建一个对象:

 class Bf
    {
        public string Key { get; set; }

        public string Value { get; set; }

        public Bf()
        {

        }

        public Bf(string key, string value)
        {
            this.Key = key;
            this.Value = value;
        }

        public override string ToString()
        {
            return string.Format("key:{0},value:{1}", this.Key, this.Value);
        }
    }
Source Code

 

这个是对物件对象,有key和value两个特性。

我们需要把拆分好的数据临时存储起来,现在我们把它们存放在一个List<T>集合中:

 

class Bg
    {
        private List<Bf> _list = new List<Bf>();

        public void Add(Bf bf)
        {
            _list.Add(bf);
        }

        public virtual IEnumerable<Bf> Bfs
        {
            get
            {
                return this._list;
            }
        }

    }
Source Code

 

接下来,我们写一个Helper类,处理分割与输出结果的相关类:

 class SplitHelper
    {
        public string OriginalString { get; set; }

        public char Group_Separator { get; set; }

        public char Item_Separator { get; set; }

        public SplitHelper()
        {

        }

        public SplitHelper(string originalString, char group_separator, char item_separator)
        {
            this.OriginalString = originalString;
            this.Group_Separator = group_separator;
            this.Item_Separator = item_separator;
        }

        private Bg bg = new Bg();
        public void SplitProcess()
        {
            foreach (var item in this.OriginalString.Split(Group_Separator))
            {
                string[] arr = item.Split(this.Item_Separator);
                if (arr.Length != 2) continue;
                Bf objBf = new Bf();
                objBf.Key = arr[0];
                objBf.Value = arr[1];
                bg.Add(objBf);                   
            }
        }

        public void Output()
        {
            bg.Bfs.ForEach(delegate (Bf bg)
            {
                Console.WriteLine(bg.ToString());
            });
        }
    }
Source Code

 

在控制台测试代码:

 

posted @ 2017-12-26 14:29  Insus.NET  阅读(744)  评论(1编辑  收藏  举报