Takes a string of the form "x1=y1,x2=y2,..." and returns Map - CSharp System

CSharp examples for System:String Convert

Description

Takes a string of the form "x1=y1,x2=y2,..." and returns Map

Demo Code


using System.Threading.Tasks;
using System.Text.RegularExpressions;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System;//from ww  w . j  a va2  s . co  m

public class Main{
        /// <summary>
        /// Takes a string of the form "x1=y1,x2=y2,..." and returns Map
        /// </summary>
        /// <param name="map">A string of the form "x1=y1,x2=y2,..."</param>
        /// <returns>A Map m is returned such that m.get(xn) = yn</returns>
        public static Dictionary<string, string> MapStringToMap(string map)
        {
            string[] m = map.Split(new[] {'[', ',', ';', ']'});
            var res = new Dictionary<string, string>();
            foreach (string str in m)
            {
                int index = str.LastIndexOf('=');
                string key = str.Substring(0, index);
                string val = str.Substring(index + 1);
                res.Add(key.Trim(), val.Trim());
            }
            return res;
        }
        public static string Trim(Object obj, int maxWidth)
        {
            return Trim(obj.ToString(), maxWidth);
        }
        /// <summary>
        /// Returns s if it's at most maxWidth chars, otherwise chops right side to fit.
        /// </summary>
        public static string Trim(string s, int maxWidth)
        {
            if (s.Length <= maxWidth)
            {
                return (s);
            }
            return (s.Substring(0, maxWidth));
        }
        /// <summary>
        /// Splits the given string using the given regex as delimiters.
        /// This method is the same as the string.Split() method 
        /// (except it throws the results in a List), and is included 
        /// just to give a call that is parallel to the other static regex methods in this class.
        /// </summary>
        /// <param name="str">string to split up</param>
        /// <param name="regex">string to compile as the regular expression</param>
        /// <returns>List of strings resulting from splitting on the regex</returns>
        public static List<string> Split(string str, string regex)
        {
            return Regex.Split(str, regex).ToList();
        }
}

Related Tutorials