0

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?

1
  • 5
    That obviously wouldn't work, as A is a string[] and not a string[][], so you certainly cannot do this in-place. You need a string[][] and then it's just a string split Commented Oct 31, 2020 at 14:39

3 Answers 3

0

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

You can check if this code helps you.

var charArray1 = A[0].ToCharArray();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.