I have one string array:
string[] A = new string[2] {"abcde", "gpfag"};
How can I split this array like this:
A[1] = new string[5] {"a", "b", "c", "d", "e"};
Any idea?
You already have this:
for (int i = 0; i < A[1].Length; i++)
{
Console.WriteLine(A[1][i]);
}
Results:
g p f a g
See it work here:
https://dotnetfiddle.net/I6UGBQ
The only difference is it's read-only; you can't assign characters back into the string by position. But you can still do this:
A[1] = new string(new char[] {'a', 'b', 'c', 'd', 'e'});
Note this uses char values, because a string is a sequence of characters. What you wanted wouldn't work, because you were trying to use a sequence of one-character strings, which is not the same thing.
Certainly you can't do it in-place as Camilo Terevinto suggested in the comments, you have to store the flattened result in a new collection.
You can use Enumerable.Select to flatten the initial string array and further use ToCharArray extension method to flatten the string and map it back again to strings as ToCharArray converts it to individual characters.
using System;
using System.Linq;
using System.Reflection.Metadata.Ecma335;
namespace TestApp
{
public class Program
{
public static void Main(string[] args)
{
string[] A = new string[2] { "abcde", "gpfag" };
string[][] flattened = A.Select((item) => item.ToCharArray().Select((inner) => new String(inner, 1)).ToArray())
.ToArray();
foreach (string[] outer in flattened)
{
foreach (string inner in outer)
{
Console.WriteLine(inner);
}
}
}
}
}
Outputting -
a
b
c
d
e
g
p
f
a
g
Ais astring[]and not astring[][], so you certainly cannot do this in-place. You need astring[][]and then it's just a string split