Reputation: 6595
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?
Upvotes: 3
Views: 3201
Reputation: 32770
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]
.
Upvotes: 3
Reputation: 17
Yeah, as provided above you can use ToArray() function to achieve the desirable result
"STRING".ToArray()
Upvotes: 0