I am trying to split a string that the user tiped in. For example: He types in "Hello". So I want to split this up into an array: ["H","E","L",...]. So how do I use this .split() function?
And how do I save it into an Array?
Thank you guys.
I am trying to split a string that the user tiped in. For example: He types in "Hello". So I want to split this up into an array: ["H","E","L",...]. So how do I use this .split() function?
And how do I save it into an Array?
Thank you guys.
If you want a char[] like {'H', 'e', 'l', 'l', 'o'} you can simply use ToCharArray():
string s = "Hello";
char[] letters = s.ToCharArray();
If you want a string[] like {"H", "e", "l", "l", "o"} you can do it like this:
string s = "Hello";
string[] letters = s.Select(c => c.ToString()).ToArray();
string myString = "hello" then char e = myString[1] is completely valid?.ToCharArray() call is redundant.If you want a string[] as your desired result ["H","E","L",... suggests:
string input = "Hello";
char[] chars = input.ToCharArray();
string[] asStringArray = Array.ConvertAll(chars, char.ToString);
String.ToCharArray is better than Enumerable.ToArray if the string is large because ToCharArray knows the size of the string beforehand. So it can initialize the array with the correct size without needing to resize it again and again.
The same applies to Array.ConvertAll which knows the size of the array.
Enumerable.ToArray fills a Buffer that checks if the given sequence implements ICollection<T> and if so uses its Count, so there wouldn't be much (if any) advantage in using String.ToCharArray over Enumerable.ToArray. ---- strike that, string doesn't implement ICollection<T>, so you're absolutely right.string[] asStringArray = input.Select(c => c.ToString()).ToArray();char[] myArray = myString.ToArray();
myString[0] in c#? Haven't touched it for long time.String.ToCharArray is better than Enumerable.ToArray because it can initialize the array with the correct size beforehand.string[] and not a char[]