Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

split string to string array in c# without delimiter

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
like image 668
Randeep Singh Avatar asked Jul 06 '26 13:07

Randeep Singh


2 Answers

You can achieve your goal using a bit of Linq

string[] myStringArray = myString.Select(x => x.ToString())
                                 .ToArray();
like image 113
Steve Avatar answered Jul 08 '26 02:07

Steve


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());
like image 25
Douglas Avatar answered Jul 08 '26 02:07

Douglas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!