The string class constructor takes an array of
characters to create a new string from an array of characters. The following
code snippet creates two strings. First from a string and second by direct passing
the array in the constructor.
-
- char[] chars = new char[10];
- chars[0] = 'M';
- chars[1] = 'a';
- chars[2] = 'h';
- chars[3] = 'e';
- chars[4] = 's';
- chars[5] = 'h';
- string charsStr = new string(chars);
- string charsStr2 = new string(new char[]
- {'T','h','i','s',' ','i','s',' ','a',' ','s','t','r','i','n','g'});
Here is a complete sample code:
- public void StringToCharArray()
- {
-
-
- string sentence = "Mahesh Chand";
- char[] charArr = sentence.ToCharArray();
- foreach (char ch in charArr)
- {
-
- Console.WriteLine(ch);
- }
-
-
- char[] chars = new char[10];
- chars[0] = 'M';
- chars[1] = 'a';
- chars[2] = 'h';
- chars[3] = 'e';
- chars[4] = 's';
- chars[5] = 'h';
- string charsStr = new string(chars);
- string charsStr2 = new string(new char[]
- {'T','h','i','s',' ','i','s',' ','a',' ','s','t','r','i','n','g'});
- Console.WriteLine("Chars to string: {0}", charsStr);
- Console.WriteLine("Chars to string: {0}", charsStr2);
- }
The output looks like the following: