简体   繁体   中英

Use String.Split to split by character in c#

I have a string named String1. How can I use String.Split to split it by letters into letters[].

As an example, say String1 = "Hello World" . How can I split it so that letters[0] = H , letters[1] = e , letters[2] = l , and so on.

String class in .NET has an indexer , which allows you to access the char value at specific position in a string. So, you can do something like that

var String1 = "Hello World";
var letter = String1[0]; //equals `H`
letter = String1[1]; //equals `e`

Another option is to use ToCharArray method, it copies the characters from a string instance to a character array

var String1 = "Hello World";
var array = String1.ToCharArray();

But there is no need to copy the string to a char array (unless you have a good reason for that), indexer is just enough

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM