Split string

Keywords: C#

Split a string to get the key and value of each group.

Such as string:

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

 

According to the object-oriented concept, create an object:

 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

 

This is for object objects. It has two properties: key and value.

We need to store the split data temporarily. Now we store them in a list < T > Set:

 

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

 

Next, we write a Helper class to deal with the related classes of segmentation and output results:

 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

 

Test the code at the console:

Posted by edawg on Thu, 30 Apr 2020 19:25:18 -0700