C# String.ToCharArray() 方法
String.ToCharArray() 方法用於獲取字符串的字符數組,它將該字符串的字符複製到Unicode 字符數組中。
用法:
char[] String.ToCharArray(); char[] String.ToCharArray(int start_index, int length);
參數:
- 第一種語法沒有參數,它返回完整字符串的字符數組。
- 在第二種語法中,有兩個參數:
start_index
- 從您想要將字符串字符複製到 Unicode char[] 的位置,以及length
– 要複製的字符總數。
返回值:在這兩種情況下,它都會返回char[]
。
例:
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
使用 String.ToCharArray() 方法將字符串轉換為字符數組的 C# 示例
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();
}
}
}
輸出
str:Hello world! char_arr... H e l l o w o r l d ! char_arr... w o r l d
參考:String.ToCharArray() 方法
相關用法
- C# String.ToUpperInvariant用法及代碼示例
- C# String.ToLowerInvariant用法及代碼示例
- C# String.IsNullOrEmpty()用法及代碼示例
- C# String.Copy()用法及代碼示例
- C# String.Clone()用法及代碼示例
- C# String.Insert()用法及代碼示例
- C# String.Split()用法及代碼示例
- C# String.Contains()用法及代碼示例
- C# String.Format()函數用法及代碼示例
- C# String.CopyTo()用法及代碼示例
- C# String.Compare()用法及代碼示例
- C# String.Format()方法用法及代碼示例
- C# String.IsNormalized用法及代碼示例
- C# String.IndexOf()方法用法及代碼示例
- C# StringBuilder.ToString用法及代碼示例
- C# String ToLower()用法及代碼示例
- C# String ToString()用法及代碼示例
- C# String Contains()用法及代碼示例
- C# String ToCharArray()用法及代碼示例
- C# String IndexOf()用法及代碼示例
注:本文由純淨天空篩選整理自 String.ToCharArray() method with example in C#。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。