Convert String to Character Array in C#
Given a string, the task is to convert this string into a character array in C#.
Examples:
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]
Method 1: Naive Approach
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.
Below is the implementation of the above approach:
C#
using System;
public class GFG{
static public void Main ()
{
string str = "GeeksForGeeks" ;
char [] ch = new char [str.Length];
for ( int i = 0; i < str.Length; i++) {
ch[i] = str[i];
}
foreach ( char c in ch) {
Console.WriteLine(c);
}
}
}
|
Output:
G
e
e
k
s
F
o
r
G
e
e
k
s
Method 2: Using toCharArray() Method
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#
using System;
public class GFG{
static public void Main ()
{
string str = "GeeksForGeeks" ;
char [] ch = str.ToCharArray();
foreach ( char c in ch) {
Console.WriteLine(c);
}
}
}
|
Output:
G
e
e
k
s
F
o
r
G
e
e
k
s
Last Updated :
26 May, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...