How to convert a char array to a string array?

后端 未结 4 1227
一向
一向 2021-02-14 01:52

Given:

A string dayCodes (i.e. \"MWF\" or \"MRFU\") that I need to split and create a collection of strings so I

相关标签:
4条回答
  • 2021-02-14 02:31

    You can do this:

                var dayCode = "MWF";
                var daysArray = new List<string>();
                var list = new Dictionary<string, string>{
                    {"M", "Monday"},
                    {"T", "Tuesday"},
                    {"W", "Wednesday"},
                    {"R", "Thursday"},
                    {"F", "Friday"},
                    {"S", "Saturday"},
                    {"U", "Sunday"}
                };
    
                for(int i = 0,max = dayCode.Length; i < max; i++)
                {
                    var tmp = dayCode[i].ToString();
                    if(list.ContainsKey(tmp))
                    {
                        daysArray.Add(list[tmp]);
                    }
                }
                Console.WriteLine(string.Join(",", daysArray));
    

    Output:

    enter image description here

    0 讨论(0)
  • 2021-02-14 02:32

    Just using char.ToString() would work:

    var daysArray = days.ToCharArray().Select( c => c.ToString()).ToArray();
    

    Alternatively, and a better solution in my mind why don't you use the string directly with a dictionary for the mapping:

    var daysArray = days.Select( c => dayMapping[c]).ToArray();
    

    with dayMapping just a Dictionary<char, string> that maps to the full day name:

    Dictionary<char, string> dayMapping = new Dictionary<char,string>()
    {
        {  'M', "Monday" },
        {  'T', "Tuesday" }
        //and so on
    }
    
    0 讨论(0)
  • 2021-02-14 02:35

    To answer the question in the title for anyone finding this in a search...(not the problem as described...thats one of earlier posts.)

    var t = "ABC";
    var s = t.ToCharArray().Select(c => c.ToString()).ToArray();

    0 讨论(0)
  • 2021-02-14 02:46
    char[] daysCodeArray = days.ToCharArray();
    string[] daysArray = daysCodeArray.Select(el =>
    {
        switch (el)
        {
            case 'M':
                return "Monday";
    
            case 'T':
                return "Tuesday";
    
            case 'W':
                return "Wednesday";
    
            case 'R':
                return "Thursday";
    
            case 'F':
                return "Friday";
    
            case 'S':
                return "Saturday";
    
            case 'U':
                return "Sunday";
         }
         throw new ArgumentException("Invalid day code");
    }).ToArray();
    

    You can change the lambda into a separate method if you want.

    0 讨论(0)
提交回复
热议问题