How do I convert a single char to a string?
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
}
Use the .ToString() Method
String myString = "Hello, World";
foreach (Char c in myString)
{
String cString = c.ToString();
}
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
With C# 6 interpolation:
char ch = 'A';
string s = $"{ch}";
This shaves a few bytes. :)
It seems that the obvious thing to do is this:
String cString = c.ToString()
Create a new string from the char.
String cString = new String(new char[] { c });
or
String cString = c.ToString();