如何将单个字符串转换为字符串?

Ian*_*ien 45 c# string casting char

我想枚举一个string而不是它返回chars我希望迭代变量是类型的string.这可能不可能让迭代类型成为一个string迭代这个字符串的最有效方法是什么?

我是否需要string在循环的每次迭代中创建一个新对象,或者我可以以某种方式执行转换?

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
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*all 63

使用.ToString()方法

String myString = "Hello, World";
foreach (Char c in myString)
{
    String cString = c.ToString(); 
}
Run Code Online (Sandbox Code Playgroud)

  • 考虑使用C#类型`string`和`char`而不是CLR类型.最终相同但在C#中可以说更正确. (2认同)

Luk*_*don 10

你有两个选择.创建string对象或调用ToString方法.

String cString = c.ToString();
String cString2 = new String(c, 1); // second parameter indicates
                                    // how many times it should be repeated
Run Code Online (Sandbox Code Playgroud)


Ian*_*ien 5

似乎显而易见的事情是这样的:

String cString = c.ToString()
Run Code Online (Sandbox Code Playgroud)


sea*_*ean 5

使用C#6插值:

char ch = 'A';
string s = $"{ch}";
Run Code Online (Sandbox Code Playgroud)

这将节省一些字节。:)