jaxben
jaxben

Reputation: 21

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.

Upvotes: 0

Views: 80

Answers (1)

Pavel Anikhouski
Pavel Anikhouski

Reputation: 23218

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

Upvotes: 5

Related Questions