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)
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)
| 归档时间: |
|
| 查看次数: |
87862 次 |
| 最近记录: |