如何转换char数组到字符串数组? [英] How to convert a char array to a string array?

查看:176
本文介绍了如何转换char数组到字符串数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑:

一个字符串 dayCodes (即三五MRFU),我需要拆分并创建的字符串的集合,所以我可以有一天的清单周字符串(即星期一,星期三,星期五星期一,星期四,星期五,星期天 )。

A string dayCodes (i.e. "MWF" or "MRFU") that I need to split and create a collection of strings so I can have a list of day of the week strings (i.e. "Monday", "Wednesday", "Friday" or "Monday", "Thursday", "Friday", "Sunday").

// this causes a run-time exception because you can't cast Char to String
var daysArray = days.ToCharArray().Cast<string>().ToArray();

// for each dayCode, overwrite the code with the day string.
for (var i = 0; i < daysArray.Length; i++)
{
    switch (daysArray[i])
    {
        case "M":
            daysArray[i] = "Monday";
            break;

        case "T":
            daysArray[i] = "Tuesday";
            break;

        case "W":
            daysArray[i] = "Wednesday";
            break;

        case "R":
            daysArray[i] = "Thursday";
            break;

        case "F":
            daysArray[i] = "Friday";
            break;

        case "S":
            daysArray[i] = "Saturday";
            break;

        case "U":
            daysArray[i] = "Sunday";
            break;
    }
 }

 daysArray[daysArray.Length - 1] = "and " + daysArray[daysArray.Length - 1];

 return string.Join(", ", daysArray);



问题:

问题是,你可以不投字符字符串我的猜测是有道理的,因为一个不从其他继承。还是你会认为,编译器会施放字符为一个字符长字符串

The problem is that you can't cast Char to String which I guess makes sense because one is not inherited from the other. Still you'd think that the compiler would cast the Char as a one character long String.

有一个快速的方法(如使用演员LT;串>())要做到这一点,所以我没有创建列表<串> 从头

Is there a quick way (like using Cast<string>()) to do this so I don't have to create a List<string> from scratch?

推荐答案

只需使用 char.ToString()将工作:

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();



dayMapping 只是一个字典<焦炭,串> 映射到全天名称:

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
}

这篇关于如何转换char数组到字符串数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆