Reputation: 11
i would like to save my grid positions of 4*4 grid with integer before quitting game.
I thought i could convert array into string and save it using player preferences for next use.
i saved the numbers in two dimensional integer array. now how to convert it into string in c#.
Upvotes: 0
Views: 285
Reputation: 12171
You can use StringBuilder
when you convert your array into string
. You can split every element in row by ","
(or any other symbol) and rows can be splited by "."
(or any other symbol), so when you will parse string to int[,]
array you don't need to know the array sizes:
public string ArrayToString(int[,] toConvert)
{
StringBuilder sb = new StringBuilder();
for (int a = 0; a < toConvert.GetLength(0);a++)
{
for (int b = 0; b < toConvert.GetLength(1);b++)
{
sb.Append(toConvert[a,b].ToString() + ",");
}
sb.Append(".");
}
return sb.ToString();
}
Then you can restore your array from string:
public int[,] ArrayFromString(string toConvert)
{
string[] rows = toConvert.Split('.');
string[] elements = rows[0].Split(',');
int[,] result = new int[rows.Length, elements.Length];
for (int a = 0; a < rows.Length; a++)
{
string[] items = rows[a].Split(',');
for (int b = 0; b < items.Length; b++)
{
result[a,b] = Convert.ToInt32(items[b]);
}
}
return result;
}
Upvotes: 3
Reputation: 618
I assume you have your result ready in temp
variable below,
var output = new string[temp.GetUpperBound(0)+1];
for (int i = 0; i<=temp.GetUpperBound(0); i++)
{
var sb = new StringBuilder(temp.GetUpperBound(1)+1);
for (int j = 0; j<=temp.GetUpperBound(1); j++)
sb.Append(temp[i,j]);
output[i] = sb.ToString();
}
Try this.
Upvotes: 1