1

What is the best way to create the matrix C?

    string A;
    char[] B = A.ToCharArray();
    string[] C = new string[B.Length];

    for (int i = 0; i < B.Length ; i++)
    {
        C[i] = B[i].ToString();
    }
2
  • You mean, aside from assigning a value to A? What's wrong with the code you posted? Commented Jun 1, 2009 at 18:34
  • 1
    One cannot be told how to create The matrix... Commented Jun 1, 2009 at 18:34

3 Answers 3

8

You just want a nicer way to do what you're doing? I suppose you could do it like this:

string   A = "ABCDEFG";
string[] C = A.Select(c => c.ToString()).ToArray();
Sign up to request clarification or add additional context in comments.

1 Comment

I have a feeling that if this guy answers with the above piece of code his professor will know real quick that it didn't come from him; no explanation necessary.
1

Another option as well as mquander's is to use Array.ConvertAll():

string[] C = Array.ConvertAll(A.ToCharArray(), c => c.ToString());

I generally prefer the LINQ approach, but ConvertAll is worth knowing about (for both arrays and lists) as it's able to use the fact that it knows the size to start with.

5 Comments

Jon, if I call .ToArray() on an enumerable then how does it cope with not knowing the size? Does it keep resizing the thing dynamically as if it were a List<>? It never occurred to me that it would have to do that, but I don't see a way around it, which seems like a real shame.
@mquander: It basically buffers it, as if you repeatedly called List.Add.
(And then converts it into an array when it detects it's got to the end.)
Things like that make me wonder why there aren't overloads of LINQ functions that are extension methods on ICollection or IList instead of IEnumerable. It seems like the extra information like indexers and counts could be used for significant micro-optimization that would help everyone out.
Count() takes account of whether the collection is an IList. It's possible that ToArray and ToList do too, but I don't know for sure.
1
using System.Text.RegularExpressions;

string[] chars = Regex.Split(s, string.Empty);

2 Comments

I was not aware Regex.Split worked that way on an empty expression. Neat.
Just found that out myself. Couldn't figure out why it wouldn't work on ".", then I remembered I have to remember at least 3 flavors of Regex syntax.

Your Answer

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