Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# string to string array

Tags:

arrays

string

c#

I have a string like this:

string example = "123456789@987654321";

I want to create a string array, and for each position in the array i want to add a letter. Something like this:

string [sizeof(example)] example2;

example2[0] = "1";
example2[1] = "2";
example2[2] = "3";

...

example2[9] = "@";

...

example[18] = "1";

and so on, each position having a character of the string example, by order.

Regardless, thanks!

like image 774
jeyejow Avatar asked Feb 18 '26 23:02

jeyejow


2 Answers

To get it as an array of strings, you can use this code:

string example = "123456789@987654321";
string[] example2 = example.ToCharArray().Select(c => c.ToString()).ToArray();

Let's break it down since you asked for an explanation in your comment:

// get the string into a char array, one character per element
char[] step1 = example.ToCharArray();

// Now let's get this into a collection of string values
IEnumerable<string> step2 = step1.Select(c => c.ToString());

// which we finally turn into an array of strings
string[] exampel2 = step2.ToArray();

As noted in comments, System.String implements IEnumerable<Char> which means the code can be shortened down to:

string example = "123456789@987654321";
string[] example2 = example.Select(c => c.ToString()).ToArray();

However, I still prefer to write out the .ToCharArray() part since the act of enumerating over characters in a linq query is usually not something I do so I would prefer this to not go unnoticed upon revisiting this code. This, however, is just my opinion.

One reason for this opinion is that you really need to know what you're intending to use those characters for since a multi-character unicode point might throw a spanner into your loop.

like image 159
Lasse V. Karlsen Avatar answered Feb 21 '26 12:02

Lasse V. Karlsen


This will do the trick:

string[] strArray = example.Select(x => x.ToString()).ToArray();
like image 21
Willy David Jr Avatar answered Feb 21 '26 12:02

Willy David Jr