3

I am wondering why there is no easy way to do this.

I just want to split a string into string array without specifying any delimiter. e. g. for my input as "Hello", I want the result as "H", "e", "l", "l", "o" i. e. an array of string.

There is a direct method given for splitting the string to character array (.ToCharArray()) and that in turn can be converted to string array, but nothing which can straight away give me string array.

Or I can't even do this:

string[] myStringArray = myString.Split(''); // Compile error
0

2 Answers 2

6

You can achieve your goal using a bit of Linq

string[] myStringArray = myString.Select(x => x.ToString())
                                 .ToArray();
Sign up to request clarification or add additional context in comments.

4 Comments

I guess you can omit the ToCharArray() part of that, since string implements IEnumerable<char>.
Yea. I know we can do that. But I was just thinking why can't we do that in a simple way. Or what we can pass to Split method.
Well, probably it was not high in the priority list of the Framework programmers and engineers. On this subject there is a famous blog article from E.Lippert that explains How many Microsoft employees does it take to change a lightbulb?
@DotnetRocks I'm pretty sure this is not at all a common thing that people might want to do, so it's not suprising that there isn't a special method just for it.
2

If you need to handle combining characters and surrogate pairs, you should use the StringInfo class for splitting your string:

var str = "𥀀𥀁𥀂𥀃";
var chars = new List<string>();
var tee = StringInfo.GetTextElementEnumerator(str);
while (tee.MoveNext())
    chars.Add(tee.GetTextElement());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.