1

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?

3
  • 10
    "is this possible?" Yes, yes it is. Commented Oct 24, 2016 at 20:12
  • 1
    Yes but sounds like a homework question. Commented Oct 24, 2016 at 20:12
  • 2
    You just did. Pour yourself a beer! Commented Oct 24, 2016 at 20:19

5 Answers 5

7

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)); 
Sign up to request clarification or add additional context in comments.

Comments

1

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()));

Comments

1

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 );
}

Comments

0
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)};

4 Comments

Let the OP do that :P
This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - From Review
@CDspace The code seems to produce the desired output.
It's giving the output as asked by the OP. And it's correct logically too. Why do you think its wrong?
0

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();

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.