How do I convert a single char to a string?

2019-04-17 19:19发布

I'd like to enumerate a string and instead of it returning chars I'd like to have the iterative variable be of type string. This probably isn't possible to have the iterative type be a string so what is the most efficient way to iterate through this string?

Do I need to create a new string object with each iteration of the loop or can I perform a cast somehow?

String myString = "Hello, World";
foreach (Char c in myString)
{
    // what I want to do in here is get a string representation of c
    // but I can't cast expression of type 'char' to type 'string'
    String cString = (String)c; // this will not compile
}

10条回答
唯我独甜
2楼-- · 2019-04-17 19:52

It seems that the obvious thing to do is this:

String cString = c.ToString()
查看更多
beautiful°
3楼-- · 2019-04-17 19:55

Use the .ToString() Method

String myString = "Hello, World";
foreach (Char c in myString)
{
    String cString = c.ToString(); 
}
查看更多
不美不萌又怎样
4楼-- · 2019-04-17 19:57

probably isn't possible to have the iterative type be a string

Sure it is:

foreach (string str in myString.Select(c => c.ToString())
{
...
}

Any of the suggestions in the other answers can be substituted for c.ToString(). Probably the most efficient by a small hair is c => new string(c, 1), which is what char.ToString() probably does under the hood.

查看更多
forever°为你锁心
5楼-- · 2019-04-17 19:58

Why not this code? Won't it be faster?

string myString = "Hello, World";
foreach( char c in myString )
{
    string cString = new string( c, 1 );
}
查看更多
放我归山
6楼-- · 2019-04-17 20:01

You have two options. Create a string object or call ToString method.

String cString = c.ToString();
String cString2 = new String(c, 1); // second parameter indicates
                                    // how many times it should be repeated
查看更多
萌系小妹纸
7楼-- · 2019-04-17 20:03
String cString = c.ToString();
查看更多
登录 后发表回答