在C#中将字符转换为字符串
给定一个字符,我们必须在C#中将其转换为字符串。
将char转换为字符串
要将字符转换为字符串,我们使用ToString()方法,我们用字符调用method,它返回将Unicode字符转换为字符串的字符串。
示例
Input:
char chr = 'X';
Function call:
string str = chr.ToString();
Output:
str: "X"C#示例将字符转换为字符串
在此示例中,我们有一个字符并将其转换为字符串,也有一个字符串并将所有字符转换为字符串中的字符串并打印类型和值。
using System;
using System.Text;
namespace Test
{
class Program
{
static void Main(string[] args)
{
//角色变量
char chr = 'X';
//将char转换为字符串
string str = chr.ToString();
//打印类型和值
Console.WriteLine("Type of chr: " + chr.GetType());
Console.WriteLine("Type of str: " + str.GetType());
Console.WriteLine("chr: " + chr);
Console.WriteLine("str: " + str);
//将字符串的每个字符转换为字符串[]
string str1 = "Hello world!";
string temp_str ="";
foreach (char item in str1)
{
Console.WriteLine("value: {0}, Type: {1}", item, item.GetType());
temp_str = item.ToString();
//转换并将char打印为字符串
Console.WriteLine("value: {0}, Type: {1}", temp_str, temp_str.GetType());
}
//按ENTER退出
Console.ReadLine();
}
}
}输出结果
Type of chr: System.Char Type of str: System.String chr: X str: X value: H, Type: System.Char value: H, Type: System.String value: e, Type: System.Char value: e, Type: System.String value: l, Type: System.Char value: l, Type: System.String value: l, Type: System.Char value: l, Type: System.String value: o, Type: System.Char value: o, Type: System.String value: , Type: System.Char value: , Type: System.String value: w, Type: System.Char value: w, Type: System.String value: o, Type: System.Char value: o, Type: System.String value: r, Type: System.Char value: r, Type: System.String value: l, Type: System.Char value: l, Type: System.String value: d, Type: System.Char value: d, Type: System.String value: !, Type: System.Char value: !, Type: System.String