As has been mentioned, a string IS an array, of characters. You can use it like an array already, so there isn't really a need to convert it explicity. Perhaps if we knew what you were trying to do, we could give better advice.
tgreer
Made Her Cry
2,118 posts since Dec 2004
Reputation Points: 227
Solved Threads: 37
The two main methods of accessing the characters of a string have been mentioned here. I thought i'd also mention the string.split function. It won't split a word into characters, but it can be used to split a string into its composite substrings. I put all the methods together in a console app so you could see the similarities/differences:
class Program
{
static void Main(string[] args)
{
string helloString = "Hello World";
Console.WriteLine(helloString[0]); //reference char by index
foreach (char ch in helloString) //iterate through char collection
{
Console.Write(ch);
}
Console.WriteLine();
char[] helloChars = helloString.ToCharArray(); //explicitly convert to char array
Console.WriteLine(helloChars[0]); //ouput content of array position
foreach (char ch in helloChars) //iterate through char array
{
Console.Write(ch);
}
Console.WriteLine();
char[] seperators = { ' ' }; //declare array of characters that will mark seperation of 'words'
string[] helloStrings = helloString.Split(seperators); //split string into array of substrings
Console.WriteLine(helloStrings[0]);//output first substring
Console.WriteLine(helloStrings[1]);//output second substring
Console.ReadKey();
}
}
The first two blocks of code really highlight what has been said here. Whilst you can convert a string to an array of characters, it is in fact already an array of characters. You can access each by index, and iterate through them the same way.
Ryshad
Nearly a Posting Virtuoso
1,307 posts since Aug 2009
Reputation Points: 512
Solved Threads: 246