Cear
Cear

Reputation: 21

Converting a string to an array with its letters

Basically what I'm trying to do is take a string

string test = "hello";

and then turn it into an array as such:

string[] testing = { "h", "he", "hel", "hell", "hello" };

is this possible?

Upvotes: 1

Views: 141

Answers (5)

deloreyk
deloreyk

Reputation: 1239

I'd recommend Dmitry's LINQ version, but if you want a simple version that uses an array like your original question:

string input = "hello";
string[] output = new string[input.Length];
for( int i = 0; i < test.Length; ++i )
{
    output[i] = test.Substring( 0, i + 1 );
}

Upvotes: 1

Tinwor
Tinwor

Reputation: 7973

You can also do something like this:

            List<string> list = new List<string>();
            for(int i = 1; i <= hello.Length; i++) {
               list.Add(hello.Substring(0,i));
            }
             Console.WriteLine(string.Join(", ", list.ToArray()));

Upvotes: 1

Giab
Giab

Reputation: 9

Yes, you use Linq.

    string test = "hello";      
    List<string> lst = new List<string>();

    int charCount = 1;

    while (charCount <= test.Length)
    {
        lst.Add(string.Join("", test.Take(charCount).ToArray()));           
        charCount++;
    }

    string[] testing = lst.ToArray();

Upvotes: 0

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

Try using Linq:

  string test = "hello";

  string[] testing = Enumerable
    .Range(1, test.Length)
    .Select(length => test.Substring(0, length))
    .ToArray();

Test:

  // h, he, hel, hell, hello
  Console.Write(string.Join(", ", testing)); 

Upvotes: 7

Vivek Nuna
Vivek Nuna

Reputation: 1

string test = "hello";
    string[] arr = new string[] {test.Substring(0,1), test.Substring(0,2), test.Substring(0,3), test.Substring(0,4), test.Substring(0,5)};

Upvotes: 0

Related Questions