拆分一個字元串,獲取每一組的key與value。 如字元串: 按照面向對象理念來解決,創建一個對象: class Bf { public string Key { get; set; } public string Value { get; set; } public Bf() { } public ...
拆分一個字元串,獲取每一組的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