I have a string "Hello". How can I copy this string into an array in words e.g 'H', 'e', 'l', 'l', 'o'.
Thanks in advance
I have a string "Hello". How can I copy this string into an array in words e.g 'H', 'e', 'l', 'l', 'o'.
Thanks in advance
I have a string "Hello". How can I copy this string into an array in words e.g 'H', 'e', 'l', 'l', 'o'.
Thanks in advance
a string is nothing more then an array of chars, so if you want to split up the strings letters into a different string array seperatly you could do something like this:
string myString = "blah";
string[] myArray= new string[myString.Length];
for(int i = 0; i<myString.Length; i++){
myArray[i] = myString[i].ToString();
}
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.
string theString = "hello";
char[] theStringAsArray = s.ToCharArray();
string theString = "hello";
char[] theStringAsArray = s.ToCharArray();
yes of course, some how i forgot about that
the simplest solution is that:
string str="hello";
char[] ch = str.ToArray();
want to knpw that sting is totally converted into char array so used foreach loop because it iterate all elements in array..
foreach(char a in ch)
{
Console.WriteLine(a);//used console application for output
}
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.
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.