Willy David Jr
Willy David Jr

Reputation: 9131

How Do I Split a String Into a string[]?

I have a string:

string strToBeSplitted = "HelloWorld";

And I am planning to split my string to an array of string. Usually we do it with char:

char[] charReturn = strToBeSplitted.ToCharArray();

But what I am planning to do is return it with an array of string like this one:

string[] strReturn = strToBeSplitted ???
//Which contains strReturn[0] = "H"; and so on...

I want to return an array of string but I cannot figure out how to do this unless I do this manually by converting it to char then to a new string like StringBuilder.

Upvotes: 2

Views: 282

Answers (3)

Slai
Slai

Reputation: 22876

For completeness, RegEx approach to split between characters:

string[] charReturn = Regex.Split("HelloWorld", "(?!^)(?<!$)");

Upvotes: 0

Daniel
Daniel

Reputation: 2804

You can use Linq to quickly transform it:

strToBeSplitted.Select(c => c.ToString()).ToArray();

Upvotes: 1

sujith karivelil
sujith karivelil

Reputation: 29006

You can use .Select which will iterate through each characters in the given string, and .ToString() will help you to convert a character to a string, and finally .ToArray() can help you to store the IEnumerable<string> into a string array. Hope that this is what you are looking for:

string strToBeSplitted = "HelloWorld";
string[] strArray = strToBeSplitted.Select(x => x.ToString()).ToArray();

Upvotes: 7

Related Questions