-4

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.

1

3 Answers 3

5

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();
Sign up to request clarification or add additional context in comments.

3 Comments

Could you please add that if string myString = "hello" then char e = myString[1] is completely valid?
In the second case, .ToCharArray() call is redundant.
@IvanStoev right, thx. Updated.
4

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.

2 Comments

According to referencesource, 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.
Good to know since my approach would have been string[] asStringArray = input.Select(c => c.ToString()).ToArray();
3
char[] myArray = myString.ToArray();

5 Comments

Is it possible to just do myString[0] in c#? Haven't touched it for long time.
Yes, myString[0] would return the first char of that string. You could iterate over the string length I guess!
I wasn't talking about an array. Just random question whether it'd throw an error or not. Tq FYI. :)
String.ToCharArray is better than Enumerable.ToArray because it can initialize the array with the correct size beforehand.
Seems OP asks for a string[] and not a char[]

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.