I am trying to write some C# code for Unity that will read from a text file, store each line in a string array, and then convert it to a 2D char array.
The error occurs at:
void ReadFile()
{
StreamReader read = new StreamReader(Application.dataPath + "/Maze1.txt");
int length = read.ReadLine().Length;
maze = new string[length, length];
line = new string[length];
while(!read.EndOfStream)
{
for (int i = 0; i <= length; i++)
{
line[i] = read.ReadLine();
}
for( int i = 0; i <= length; i++)
{
for( int j = 0; j <= length; j++)
{
maze[i,j] = line[i].Split(','); // <---This line is the issue.
}
}
}
}
The Exact error I am getting is:
Cannot Implicitly convert type 'string[]' to 'string'
What does this error mean and how do I fix the code?
I have a feeling you meant to do this:
for( int i = 0; i <= length; i++)
{
var parts = line[i].Split(',');
for( int j = 0; j <= length; j++)
{
maze[i,j] = parts[j];
}
}
As error says maze[i,j] will take a string but line[i].Split(','); would return a string[].
The better data structure for the maze is in your case an array of arrays, instead of the 2d array. So you can assign the result of the split operation directly without the extra copy:
StreamReader read = new StreamReader(Application.dataPath + "/Maze1.txt");
string firstLine = read.ReadLine();
int length = firstLine.Length;
string[][] maze = new string[length][];
maze[0] = firstLine.Split(',');
while(!read.EndOfStream)
{
for (int i = 1; i < length; i++)
{
maze[i] = read.ReadLine().Split(',');
}
}
You can then access the maze similar to the 2d array:
var aMazeChar = maze[i][j];
Related
I want to remove a specific object from an array, put it in a smaller array without getting out of range. This is what I've tried but it won't work.
Skateboard[] newSkateboard = new Skateboard[_skateboards.Length - 1];
for (int i = 0; i < _skateboards.Length; i++)
{
if (skateboard.Code != _skateboards[i].Code)
{
newSkateboard[i] = _skateboards[i];
}
}
Sure.
var j = 0;
for (int i = 0; i < _skateboards.Length; i++)
{
if (skateboard.Code != _skateboards[i].Code)
{
newSkateboard[j] = _skateboards[i];
j = j + 1;
}
}
Hello everyone I am new to programming in c#, what I am going to do is that I want to convert the 2D string array to 2D integer array, the reason for this conversion is that I want to pass that integer array to another method for some calculation. Thanks in advance for helping.
public void Matrix()
{
int a = int.Parse(txtRowA.Text);
int b = int.Parse(txtColA.Text);
Random rnd = new Random();
int[,] matrixA = new int[a, b];
string matrixString = "";
for (int i = 0; i < a; i++)
{
for (int j = 0; j < b; j++)
{
matrixA[i, j] = rnd.Next(1, 100);
matrixString += matrixA[i, j];
matrixString += " ";
}
matrixString += Environment.NewLine;
}
txtA.Text = matrixString;
txtA.TextAlign = HorizontalAlignment.Center;
}
Your code is actually pretty close. Try this:
private Random rnd = new Random();
public int[,] Matrix(int a, int b)
{
int[,] matrixA = new int[a, b];
for (int i = 0; i < a; i++)
{
for (int j = 0; j < b; j++)
{
matrixA[i, j] = rnd.Next(1, 100);
}
}
return matrixA;
}
What you have there is a function that does not rely on any WinForms controls and will produce your int[,] quickly and efficiently.
Let the calling code work with the WinForms controls:
int a = int.Parse(txtRowA.Text);
int b = int.Parse(txtColA.Text);
int[,] matrix = Matrix(a, b);
Now you can pass the matrix to anything that requires an int[,].
If you need to display the matrix then create a separate function for that:
public string MatrixToString(int[,] matrix)
{
StringBuilder sb = new();
for (int i = 0; i < matrix.GetLength(0); i++)
{
string line = "";
for (int j = 0; j < matrix.GetLength(1); j++)
{
line += $"{matrix[i, j]} ";
}
sb.AppendLine(line.Trim());
}
return sb.ToString();
}
Your calling code would look like this:
int a = int.Parse(txtRowA.Text);
int b = int.Parse(txtColA.Text);
int[,] matrix = Matrix(a, b);
UseTheMatrix(matrix);
txtA.Text = MatrixToString(matrix);
txtA.TextAlign = HorizontalAlignment.Center;
A sample run produces:
You can use List as a helper to store the elements of the array extracted from the string, but first I replaced the SPACE between elements in your string with a special character '|' as a separator to make it easier to extract the numbers from the string.
you can do somthing like this:
public static int[,] ConvertToInt(string matrix)
{
List<List<int>> initial = new List<List<int>>();
int lineNumber = 0;
int currenctIndex = 0;
int lastIndex = 0;
int digitCount = 0;
initial.Add(new List<int>());
foreach (char myChar in matrix.ToCharArray())
{
if (myChar == '|')
{
initial[lineNumber].Add(int.Parse(matrix.Substring(lastIndex, digitCount)));
lastIndex = currenctIndex+1;
digitCount = 0;
}
else
digitCount++;
if (myChar == '\n')
{
lineNumber++;
if(currenctIndex < matrix.Length-1)
initial.Add(new List<int>());
}
currenctIndex++;
}
int[,] myInt = new int[initial.Count, initial[0].Count];
for (int i = 0; i < initial.Count; i++)
for (int j = 0; j < initial[i].Count; j++)
myInt[i, j] = initial[i][j];
return myInt;
}
I would like to create an array of an array from a text file...
There are 20000 line with 21 strings in each line separated by ',' .
I would like to read each line and make it into an array , each line being a new array within.
So I wanted to create the jagged array by starting it like this:
string[][] SqlArray = new string[200000][21];
But it gives: ERROR MESSAGE : Invalid rank specifier: expected ',' or ]
How would I create this array or initialize it?
I will be populating the data in the array like this:
while (true)
{
string theline = readIn.ReadLine();
if (theline == null) break;
string[] workingArray = theline.Split(',');
for (int i = 0; i < workingArray.Length; i++)
{
for (int k = 0; k < 20; k++)
{
SqlArray[i][k] = workingArray[k];
}
}
}
Thank you
That type of initialization only works in Java. You must declare an array of arrays then initialize each in a loop.
string[][] SqlArray = new string[21][];
for(int index = 0; index < SqlArray.Length; index++)
{
SqlArray[index] = new string[2000000];
}
Alternatively, you can use a non-jagged array. It will probably work for what you need.
string[,] SqlArray = new string[21 , 2000000];
It can be accessed like so:
SqlArray[2,6264] = x;
To anyone who is interested this is how I ended up implementing it:
TextReader readIn = File.OpenText("..\\..\\datafile.txt");
string[][] SqlArray = new string[rowNumCreate][];
int e = 0;
while (true)
{
string theline = readIn.ReadLine();
if (theline == null) break;
string[] workingArray = theline.Split(',');
SqlArray[e] = new string[valuesInRow +1];
for (int k = 0; k < workingArray.Length; k++)
{
SqlArray[e][k] = workingArray[k];
}
e++;
}
The file being read is a simple mock database set as a flat file that was auto-generated to test an algorithm that I am implementing, which works with jagged arrays; hence instead of working with a data base I just created this for ease of use and to increase and decrease size at will.
Here is the code to build the text file:
Random skill_id;
skill_id = new Random();
// int counter =0;
string seedvalue = TicksToString();
int rowNumCreate = 200000;
int valuesInRow = 20;
string lineInFile = seedvalue;
string delimiter = ",";
for (int i = 0; i < rowNumCreate; i++)
{
for (int t = 0; t < valuesInRow; t++)
{
int skill = skill_id.Next(40);
string SCon = Convert.ToString(skill);
lineInFile += delimiter + SCon;
}
if (rowNumCreate >= i + 1)
{
dataFile.WriteLine(lineInFile);
lineInFile = "";
string userPK = TicksToString();
lineInFile += userPK;
}
}
dataFile.Close();
public static string TicksToString()
{
long ms = DateTime.Now.Second;
long ms2 = DateTime.Now.Millisecond;
Random seeds;
seeds = new Random();
int ran = seeds.GetHashCode();
return string.Format("{0:X}{1:X}{2:X}", ms, ms2, ran).ToLower();
}
I am still a student so not sure if the code is A-grade but it works :)
So i'm trying to read a txt file in string theMap and then make a copy of theMap in map and return map. Also im trying to read the Txt file in 2d string. Then the returned array which is map. I want to print it at the console and there is the "Cannot apply indexing with [] to an expression of type 'method group'" problem here is the code also.
public static string[,] Reader()
{
string theMap = System.IO.File.ReadAllText(#"C:\Users\Public\Console Slayer\Map\map.txt");
int k = 0, l = 0;
string[,] map = new string[11,54];
foreach (var row in theMap.Split('\n'))
{
foreach (var col in row.Trim().Split(' '))
{
map[l,k] = (col.Trim());
l++;
}
k++;
}
return map;
}
public static void Printer()
{
for (int y = 0; y < 11; y++)
{
for (int x = 0; x < 54; x++)
{
Console.Write(Reader[y,x]);
}
Console.WriteLine();
}
}
static void Main()
{
Reader();
Printer();
}
Reader is a method. You cannot index it, but you can index the result of it:
Console.Write(Reader()[y,x]);
// ^ You need these parens to invoke the method.
However, this will invoke the function for every loop, reading the file in 11 * 54 = 594 times! Read the file once and store the result instead; there is no need to call this method on each loop iteration:
var data = Reader();
for (int y = 0; y < 11; y++)
{
for (int x = 0; x < 54; x++)
{
Console.Write(data[y,x]);
}
Console.WriteLine();
}
if (cmd == "card_request") {
Debug.Log("FOund cards");
ISFSObject responseParams = (SFSObject)evt.Params["params"];
Debug.Log(responseParams.GetClass("cards").ToString());
SFSArray data = (SFSArray)responseParams.GetSFSArray("cards");
Debug.Log(data.GetUtfString(0));
//for (int i = 0; i < data.GetUtfString(0).IndexOf("value"); i++) {
firstSplit = data.GetUtfString(0).Split(';');
Debug.Log(firstSplit);
//}
for (int i = 0; i < firstSplit[0].IndexOf("value"); i++) {
secondSplit = firstSplit[0].Split(':');
Debug.Log(secondSplit);
}
for (int i = 0; i < secondSplit[0].IndexOf("value"); i++) {
thirdSplit = secondSplit[0].Split(',');
Debug.Log(thirdSplit);
}
}
the data is coming fine at this line Debug.Log(data.GetUtfString(0)); But when I try to split it it gives errors. Somebody can please suggest me the effective way to split UTF string. Null exceptions occurs at secondSplit and thirdSplit