this string is given :
S#####
.....#
#.####
#.####
...#.G
##...#
and I want to convert it into a 6x6 char array.I know that I can fill the fields like this :
charName[0,0] ='S';
charName[0,1] ='#';
charName[0,2] ='#';
charName[0,3] ='#';
charName[0,4] ='#';
charName[0,5] ='#';
However this cost much time and I think there is a better way to do it. Thank you for any kind of help :)
Simply split by newlines:
var s="..."; // your initial string
var arr=s.Split(new[] { Environment.NewLine });
// you can then get your characters like:
var ch=arr[0][2]; // would be # in your example
It is not very clear what you are asking, but I guess you are asking for the way to initialise array. So this is how:
char[,] charName = new char[6,6] {
{'S', '#', '#', '#', '#', '#' },
{'.', '.', '.', '.', '.', '#' },
{'#', '.', '#', '#', '#', '#' },
{'#', '.', '#', '#', '#', '#' },
{'.', '.', '.', '#', '.', 'G' },
{'#', '#', '.', '.', '.', '#' },
};
Though this will not work if your data is arbitrary.
Can you try this one..
static void Main(string[] args)
{
char[,] charArray = new char[6, 6];
Add(0, ref charArray, 'S','#','#','#','#','#');
Add(1, ref charArray, '.', '.', '.', '.', '.', '#');
Add(2, ref charArray, '#', '.', '#', '#', '#', '#');
Add(3, ref charArray, '#', '.', '#', '#', '#', '#');
Add(4, ref charArray, '.', '.', '.', '#', '.', 'G');
Add(5, ref charArray, '#', '#', '.', '.', '.', '#');
}
public static void Add(int index, ref char[,] array, params char[] parameters)
{
for (int i = 0; i < parameters.Length; i++)
{
array[index, i] = parameters[i];
}
}
I take it as your string is a multiline one. So it must have '\\n' at the end of each line except the last one. So you first should split the string into a array of lines. Then from each line take each character and put it into the character array.
Here it is,
string input = "S#####\n.....#\n#.####\n#.####\n...#.G\n##...#";
char[,] charArray = new char[6, 6];
var lines = input.Split(new [] { '\n' });
int row = 0;
foreach (string line in lines)
{
int column = 0;
foreach (char character in line)
{
charArray[row, column] = character;
column++;
}
row++;
}
Console.ReadKey();
Finally the charArray (multidimensional array) will hold your string characters.
//Single-string matrix:
String input = @"S#####
.....#
#.####
#.####
...#.G
##...#";
var arr = input.Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
//Result "S" will be arr[0][0].ToString()
////Result "#" will be arr[0][0].ToString()
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.