简体   繁体   中英

how to init a 2d matrix of chars from strings C#

I would like to create a 2D matrix in C#.
I have the following example code in C++

https://www.geeksforgeeks.org/search-a-word-in-a-2d-grid-of-characters/

I would like to init the matrix like they did in C++

int main()
{
    char grid[R][C] = {"GEEKSFORGEEKS",
                       "GEEKSQUIZGEEK",
                       "IDEQAPRACTICE"
                      };

    patternSearch(grid, "GEEKS");
 ....

Here is my code in C#

   List<string> rows = new List<string> {"GEEKSFORGEEKS", "GEEKSQUIZGEEK", "IDEQAPRACTICE"};

            char[,] grid = new char[rows.Count, rows[0].Length];

            for (int r = 0; r < rows.Count; r++)
            {
                char[] charArray = rows[r].ToCharArray();
                for (int c = 0; c < charArray.Length; c++)
                {
                    grid[r, c] = charArray[c];
                }
            }

Is there a way to init the matrix like in c++? converting string to char array, or this is done easily in c++ because we can cast and manage the memory differently?

string is not a char[] , there is no implicit or explicit conversion between the two. The way to get an array of characters from a string is calling the extension method Enumerable.ToArray() ( string implements IEnumerable<char> ) or the almost legacy String.ToCharArray()

With that in mind the syntax you are looking for is:

char[][] grid = { "GEEKSFORGEEKS".ToArray(),
                  "GEEKSQUIZGEEK".ToArray(),
                  "IDEQAPRACTICE".ToArray() };

Now, if you try to get a char[,] you will run into a brick wall; the c# syntax lets you do the following:

char[][] grid = { { `G`, `E`, `E`, ... },
                  { `G`, `E`, `E`, ... }
                  { `I`, `D`, `E`, ... } };

But, again, because a string literal isn't a char of characters, the compiler will simply balk at:

char[][] grid = { { "GEEKSFORGEEKS" },
                  { "GEEKSQUIZGEEK" }
                  { "IDEQAPRACTICE" } };

And it will simply give you a compile time error informing you that a string is not a char . The actual type of that initialization would be string[,] with size [3, 1] .

是的,如上所述,您可以使用ToArray()函数来实现理想的结果

"STRING".ToArray()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM