在C#中将字符串转换为字符数组

给定一个字符串,我们必须在C#中将其转换为字符数组。

将字符串转换为char []

为了在char [](字符数组)中转换给定的字符串,我们使用String类的方法,用该字符串调用它并返回一个characters数组,它将string的字符转换为Unicode字符数组。String.ToCharArray()

示例

    Input:
    string str = "Hello world!";
    
    Function call:
    char[] char_arr = str.ToCharArray();

    Output:
    char_arr: H e l l o   w o r l d !

C#使用方法将字符串转换为字符数组的示例String.ToCharArray()

using System;
using System.Text;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            //字符串变量
            string str = "Hello world!";

            //将字符串转换为char []
            char[] char_arr = str.ToCharArray();

            Console.WriteLine("str: " + str);

            //打印字符[]
            Console.WriteLine("char_arr...");
            foreach (char item in char_arr)
            {
                Console.Write(item + " ");
            }
            Console.WriteLine();

            //printing types of string & char[]
            Console.WriteLine("Type of str: " + str.GetType());
            Console.WriteLine("Type of char_arr: " + char_arr.GetType());

            //按ENTER退出
            Console.ReadLine();
        }
    }
}

输出结果

str: Hello world!
char_arr...
H e l l o   w o r l d !
Type of str: System.String
Type of char_arr: System.Char[]