C#String.ToCharArray()方法 (C# String.ToCharArray() Method)
String.ToCharArray() method is used to get the character array of a string, it copies the characters of a this string to a Unicode character array.
String.ToCharArray()方法用于获取字符串的字符数组,它将此字符串的字符复制到Unicode字符数组。
Syntax:
句法:
char[] String.ToCharArray();
char[] String.ToCharArray(int start_index, int length);
Parameter:
参数:
In first syntax there is no parameter, it returns character array of complete string.
在第一种语法中,没有参数,它返回完整字符串的字符数组。
In second syntax, there are two parameters: start_index - from where you want to copies the string characters to the Unicode char[], and length – total number of characters to be copied.
在第二语法中,有两个参数:START_INDEX -从要在哪里复制字符串中的字符为Unicode字符[],和长度 -字符总数被复制。
Return value: In both of the cases, it returns char[].
返回值:在两种情况下,它都返回char [] 。
Example:
例:
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 !
Input:
string str = "Hello world!";
Function call:
//converting 5 characters from 6th index
char[] char_arr = str.ToCharArray(6, 5);
Output:
char_arr: w o r l d
C#使用String.ToCharArray()方法将字符串转换为字符数组的示例 (C# Example to convert string to characters array using String.ToCharArray() method)
using System;
using System.Text;
namespace Test
{
class Program
{
static void Main(string[] args)
{
//string variable
string str = "Hello world!";
char[] char_arr = str.ToCharArray();
Console.WriteLine("str: " + str);
//printing char[]
Console.WriteLine("char_arr...");
foreach (char item in char_arr)
{
Console.Write(item + " ");
}
Console.WriteLine();
//converting 5 characters from 6th index
char_arr = str.ToCharArray(6, 5);
//printing char[]
Console.WriteLine("char_arr...");
foreach (char item in char_arr)
{
Console.Write(item + " ");
}
Console.WriteLine();
//hit ENTER to exit
Console.ReadLine();
}
}
}
Output
输出量
str: Hello world!
char_arr...
H e l l o w o r l d !
char_arr...
w o r l d
Reference: String.ToCharArray() Method
翻译自: https://www.includehelp.com/dot-net/string-tochararray-method-with-example-in-c-sharp.aspx