How do I convert a single char to a string?

后端 未结 11 1735
醉梦人生
醉梦人生 2020-12-18 17:24

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 pro

相关标签:
11条回答
  • 2020-12-18 18:16

    With C# 6 interpolation:

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

    This shaves a few bytes. :)

    0 讨论(0)
  • 2020-12-18 18:17

    It seems that the obvious thing to do is this:

    String cString = c.ToString()
    
    0 讨论(0)
  • 2020-12-18 18:20

    Create an extension method:

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

    and loop through strings:

    string s = "123456";
    foreach (string c in s.GetCharsAsStrings())
    {
        //...
    }
    
    0 讨论(0)
  • 2020-12-18 18:20

    Did you try:

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

    0 讨论(0)
  • 2020-12-18 18:24

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

    string myString = "Hello, World";
    foreach( char c in myString )
    {
        string cString = new string( c, 1 );
    }
    
    0 讨论(0)
提交回复
热议问题