当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


C# String转Character Array用法及代码示例

给定 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


相关用法


注:本文由纯净天空筛选整理自SHUBHAMSINGH10大神的英文原创作品 Convert String to Character Array in C#。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。