給定 string ,任務是將該字符串轉換為 C# 中的字符數組。
例子:
Input: string Output: [s, t, r, i, n, g] Input: GeeksForGeeks Output: [G, e, e, k, s, F, o, r, G, e, e, k, s]
方法 1:簡單方法
Step 1: Get the string.
Step 2: Create a character array of the same length as of string.
Step 3: Traverse over the string to copy character at the i’th index of string to i’th index in the array.
Step 4:Return or perform the operation on the character array.
下麵是上述方法的實現:
C#
// C# program to Convert a string
// to a Character array
// using Naive Approach
using System;
public class GFG{
static public void Main ()
{
string str = "GeeksForGeeks";
// Creating array of string length
char[] ch = new char[str.Length];
// Copy character by character into array
for (int i = 0; i < str.Length; i++) {
ch[i] = str[i];
}
// Printing content of array
foreach (char c in ch) {
Console.WriteLine(c);
}
}
}
輸出:
G e e k s F o r G e e k s
方法二:使用到字符數組()方法
Step 1: Get the string.
Step 2: Create a character array of same length as of string.
Step 3: Store the array return by toCharArray() method.
Step 4: Return or perform operation on character array.
C#
// C# program to Convert a string
// to a Character array
// using ToCharArray method
using System;
public class GFG{
static public void Main ()
{
string str = "GeeksForGeeks";
// Creating array of string length
// Copy character by character into array
char[] ch = str.ToCharArray();
// Printing content of array
foreach (char c in ch) {
Console.WriteLine(c);
}
}
}
輸出:
G e e k s F o r G e e k s
相關用法
- C# String Clone()用法及代碼示例
- C# String Compare()用法及代碼示例
- C# String CompareOrdinal()用法及代碼示例
- C# String CompareTo()用法及代碼示例
- C# String Concat()用法及代碼示例
- C# String Contains()用法及代碼示例
- C# String Copy()用法及代碼示例
- C# String CopyTo()用法及代碼示例
- C# String EndsWith()用法及代碼示例
- C# String Equals()用法及代碼示例
- C# String Format()用法及代碼示例
- C# String GetEnumerator()用法及代碼示例
- C# String IndexOf()用法及代碼示例
- C# String Insert()用法及代碼示例
- C# String IsInterned()用法及代碼示例
- C# String IsNormalized()用法及代碼示例
- C# String IsNullOrEmpty()用法及代碼示例
- C# String IsNullOrWhiteSpace()用法及代碼示例
- C# String Join()用法及代碼示例
- C# String LastIndexOf()用法及代碼示例
- C# String LastIndexOfAny()用法及代碼示例
- C# String Normalize()用法及代碼示例
- C# String PadLeft()用法及代碼示例
- C# String PadRight()用法及代碼示例
- C# String Remove()用法及代碼示例
注:本文由純淨天空篩選整理自SHUBHAMSINGH10大神的英文原創作品 Convert String to Character Array in C#。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。