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

69
我想枚举一个字符串,而不是返回字符,我希望迭代变量的类型为字符串。可能无法将迭代类型设置为字符串,那么最有效的方法是什么来遍历这个字符串呢?
在循环的每次迭代中,我需要创建一个新的字符串对象吗,还是可以进行某种类型转换?
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
}
12个回答

86

使用 .ToString() 方法

String myString = "Hello, World";
foreach (Char c in myString)
{
    String cString = c.ToString(); 
}

3
考虑使用C#类型stringchar,而不是CLR类型。最终结果相同,但在C#中更正确。 - andleer
1
这条评论是针对他的,不是你。别担心。 - andleer
1
@tom_mai78101,我再次查看这个问题,我认为我在抱怨中没有人解释为什么将“char”转换为“string”无法工作或显然不能编译。 - Drew Chapin
1
看起来是可以工作的,但为什么我们不能只使用内置的语法方式来进行显式转换呢?例如:string s = (string) c - TheInitializer
所提到的人的理由,虽然不错,但仍然只是一种观点。人们可以同意或不同意。至于我支持默认规则选择的原因,是因为它很可能是经过一段时间的选择,并且不仅仅是一个人参与,而且有充分的理由。 - undefined
显示剩余14条评论

15

你有两个选项。创建一个string对象或调用ToString方法。

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

7

使用C# 6中的内插法:

char ch = 'A';
string s = $"{ch}";

这可以减少一些字节数。:)

5

看起来显而易见的做法是:

String cString = c.ToString()

4
从字符创建一个新的字符串。
 String cString = new String(new char[] { c });

或者

 String cString = c.ToString();

2

我最近想知道哪种方法最快,所以我对5种方法进行了基准测试。

答案是你应该使用 new String(myChar,1),因为它速度最快:

|           Method |      Mean |    Error |    StdDev | Rank |   Gen0 | Allocated |
|----------------- |----------:|---------:|----------:|-----:|-------:|----------:|
|        NewString |  10.65 ns | 0.502 ns |  1.473 ns |    1 | 0.0031 |      16 B |
|        AddString |  11.83 ns | 0.845 ns |  2.466 ns |    2 | 0.0030 |      16 B |
|     CharToString |  12.26 ns | 0.662 ns |  1.951 ns |    2 | 0.0030 |      16 B |
| NewStringPointer |  33.03 ns | 1.382 ns |  3.988 ns |    3 | 0.0030 |      16 B |
|      Interpolate | 119.31 ns | 5.351 ns | 15.525 ns |    4 | 0.0083 |      44 B |

这五种方法包括:

public string CharToString(char input) => input.ToString();
public string Interpolate(char input) => $"{input}";
public string AddString(char input) => input + "";
public string NewString(char input) => new String(input,1);
public string NewStringPointer(char input)
{
    unsafe
    {
        return new String(& input);
    }
}

你能否测试一下拥有256个字符串的表格(每个字符一个)并将其中一个复制以得到一个新的字符串吗?(如果只读使用,可能类似于克隆,如果是写入+读取,则可能需要进行深度复制。) - huseyin tugrul buyukisik
@huseyintugrulbuyukisik,你认为在克隆和只读/读写方面你在引用什么?这些概念都不适用于字符串。 - Brondahl
就像一个具有字符串字段的单例,根据用例更改其字段。 - huseyin tugrul buyukisik
我完全不知道你在说什么。但是这个基准测试非常容易运行;随时可以自己尝试一下 :) 搜索 Nick Chapsas Benchmark.NET。 - Brondahl

1
创建一个扩展方法:
public static IEnumerable<string> GetCharsAsStrings(this string value)
{
    return value.Select(c =>
           {
                //not good at all, but also a working variant
                //return string.Concat(c);

                return c.ToString();
           });
}

并循环遍历字符串:

string s = "123456";
foreach (string c in s.GetCharsAsStrings())
{
    //...
}

1

您可以使用空字符串""与加号+,请查看下面的代码:

char a = 'A';
//a_str is a string, the value of which is "A".
string a_str = ""+a;

1
看起来像(丑陋的)JavaScript代码。 - Steve B

0
为什么不用这段代码呢?它不会更快吗?
string myString = "Hello, World";
foreach( char c in myString )
{
    string cString = new string( c, 1 );
}

0
你尝试过吗:

String s = new String(new char[] { 'c' });


2
没有只接受 char 的构造函数。 - Lukasz Madon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接