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!
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.
This will do the trick:
string[] strArray = example.Select(x => x.ToString()).ToArray();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With