What I am doing is reading in from a text file, and then storing the contents in a 2D array, but my array is off by one at each row and column. Maybe this is simple and I am just not seeing it?
The contents of my text file:
0007,0007,0007,0007,0007,
0007,0007,0007,0007,0007,
0007,0007,0007,0007,0007,
0007,0007,0007,1707,0007,
0007,0007,0007,0007,0401
When my array is returned, the value 17 is located at [3,3]...it should be [4,4]. Below is my code. I've spent to much time on this already, could someone please help?
public int[,] Generate(string inputFilePath)
{
if (File.Exists(inputFilePath))
{
Dictionary<string, int> counts = GetRowAndColumnCounts(inputFilePath);
int rowCount = counts["row_count"];
int columnCount = counts["column_count"];
returnArray = new int[rowCount, columnCount];
using (StreamReader sr = File.OpenText(inputFilePath))
{
string s = "";
string[] split = null;
for (int i = 0; (s = sr.ReadLine()) != null; i++)
{
split = s.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
for (int j = 0; j < columnCount; j++)
{
returnArray[i, j] = int.Parse(split[j].Substring(0,2));
}
}
}
}
else
{
// throw new FileDoesNotExistException("Input file does not exist");
}
return returnArray;
}
Array indexes start at 0. So index 3 is the 4. element.
http://msdn.microsoft.com/en-us/library/aa288453(v=vs.71).aspx
C# arrays are zero indexed; that is, the array indexes start at zero.
Related
I have a message coming containing 48 different values seperated as:
String values = "4774,55567,44477|14555,4447,5687|416644,4447,5623|...";
I need to convert it into 16 by 3 array as:
String[,] vals = {{"4774,55567,44477"},{14555,4447,5687},{416644,4447,5623}...}
I tried using the split() function but cannot figure how to feed it into the matrix
You can split it two times:
var values = "4774,55567,44477|14555,4447,5687|416644,4447,5623";
var rows = values.Split('|');
var matrix = new string[rows.Length][];
for (var i = 0; i < rows.Length; i++)
{
matrix[i] = rows[i].Split(',');
}
and a more elegant solution using LINQ:
var values = "4774,55567,44477|14555,4447,5687|416644,4447,5623";
var data = values
.Split('|')
.Select(r => r.Split(','))
.ToArray();
EDIT: as #RandRandom pointed out, the solution above creates a jagged array. The difference is explained here: link. If the jagged array is not an option for you, to create a 2d array you need to create a matrix, specifying the dimensions [rows.Length, rows[0].Split(',').Length] and with the help of 2 for-loops assign the values:
string values = "4774,55567,44477|14555,4447,5687|416644,4447,5623";
string[] rows = values.Split('|');
string[,] matrix = new string[rows.Length, rows[0].Split(',').Length];
for (int i = 0; i < rows.Length; i++)
{
string[] rowColumns = rows[i].Split(',');
for (int j = 0; j < rowColumns.Length; j++)
{
matrix[i, j] = rowColumns[j];
}
}
You can split the string based on the | character. Then, using linq.Select(), split each line based on , and create a two-dimensional array
string[] temp = values.Split('|');
var res=temp.Select(x => x.Split(',')).ToArray();
Use Linq if you can consider the jagged array instead of 2D array:
var values = "4774,55567,44477|14555,4447,5687|416644,4447,5623";
var result = values
.Split('|')
.Select(x => x.Split(','))
.ToArray();
You can use the String.Split() method to split the string into an array of substrings, and then use a nested loop to iterate through the array and add the values to the 2D array.
Here is an example :
string values = "4774,55567,44477|14555,4447,5687|416644,4447,5623|...";
string[] substrings = values.Split('|');
string[,] vals = new string[substrings.Length,3];
for (int i = 0; i < substrings.Length; i++)
{
string[] subvalues = substrings[i].Split(',');
for (int j = 0; j < subvalues.Length; j++)
{
vals[i, j] = subvalues[j];
}
}
This will split the string values by the separator '|' and create an array of substrings. Then, it will iterate through each substring and split it again by ',' and store the result in a 2D array vals with 16 rows and 3 columns.
Try following :
string values = "4774,55567,44477|14555,4447,5687|416644,4447,5623";
String[][] vals = values.Split(new char[] { '|' }).Select(x => x.Split(new char[] { ',' }).ToArray()).ToArray();
string[,] vals2 = new string[vals.GetLength(0), vals[0].Length];
for(int i = 0; i < vals.GetLength(0); i++)
{
for(int j = 0; j < vals.Length; j++)
{
vals2[i, j] = vals[i][j];
}
}
I have data in txt like this:
flea,0,0,1,0,0,0,0,0,0,1,0,0,6,0,0,0,6
frog,0,0,1,0,0,1,1,1,1,1,0,0,4,0,0,0,5
frog,0,0,1,0,0,1,1,1,1,1,1,0,4,0,0,0,5
I need to count the number of zeros in a chosen column, for example in the first column there are 3 zeros.
Here is my code so far:
//data patch
string[] tekst = File.ReadAllLines(#"C:\zoo.txt");
//full of array
string[] tablica = tekst;
for(int s=0;s<tablica.Length;s++)
{
Console.WriteLine(tablica[s]);
}
//----------------Show all of array---------------------------//
//----------------Giv a number of column-----------------////
Console.WriteLine("Podaj kolumne");
int a = Convert.ToInt32(Console.ReadLine());
//Console.WriteLine("Podaj wiersz");
//int b = Convert.ToInt32(Console.ReadLine());
int n = tablica.Length;
int m = tablica[a].Split(',').Length;
string[,] liczby = new string[n, m];
for (int j = 0; j < n; j++)
{
int suma = 0;
for (int i = 0; i < m; i++)
{
//somethink should be here
}
}
Any ideas for solving this?
try:
//data patch
string[] tekst = File.ReadAllLines(#"C:\zoo.txt");
//full of array - you allready have a string[], no need for a new one
//string[] tablica = tekst;
for(int s=0;s<tekst.Length;s++)
{
Console.WriteLine(tekst[s]);
}
//----------------Show all of array---------------------------//
//----------------Giv a number of column-----------------////
// try to use names with some meaning for variables, for example instead of "a" use "column" for the column
Console.WriteLine("Podaj kolumne");
int column = Convert.ToInt32(Console.ReadLine());
// your result for zeros in a given column
int suma = 0;
// for each line in your string[]
foreach ( string line in tekst )
{
// get the line separated by comas
string[] lineColumns = line.Split(',');
// check if that column is a zero, remember index is base 0
if ( lineColumns[column-1] == "0" )
suma++;
}
Console.WriteLine(suma);
EDIT: Just make sure to validate that the column they ask for, really exist in your array, AND if you do not consider the first column as the one with the name, adjust this part
lineColumns[column] // instead of lineColumns[column-1]
how to normalize the complex numbers in c#?when i have saved the text file of complex number in notepad.then i want to use these complex numbers in my c# code.And can be read text file of complex number in c#?
Current code used:
using (TextReader reader = File.OpenText("a.txt"))
{
var lineCount1 = File.ReadLines("a.txt").Count();
x1 = new double[lineCount1, 512];
for (int i = 0; i < lineCount1; i++)
{
for (int j = 0; j < 512; j++)
{
string line = reader.ReadLine();
string[] bits = line.Split(' ');
x1[i, j] = double.Parse(bits[j]);
}
}
}
its not working.!!! error in last line.
Perhaps you should have something like this:
static void Main(string[] args)
{
var lines = File.ReadAllLines("a.txt");
var complexes = new Complex[lines.Length];
for (int i = 0; i < complexes.Length; i++)
{
complexes[i] = Parse(lines[i]);
}
}
private static Complex Parse(string s)
{
var split = s.Split(new char[' '], StringSplitOptions.RemoveEmptyEntries); // I guess string is something like "12 54". If you have "12 + 54i" you'l get an exception here
return new Complex(double.Parse(split[0]), double.Parse(split[1]));
}
i have text file consist of data like:
1,2
2,3
3,4
4,5
Now I want to save the data into an array. So i do split:
using (streamreader sr = new streamreader("file.txt")) {
string[] data = sr.ReadLine().Split(',');
}
however my data save in string[] while I have a GlobalDataClass array declared as double[,]. Something like this:
static class GlobalDataClass
{
public static double[,] Array = new double[4, 2];
}
I need to assign the data to the GlobalDataClass:
GlobalDataClass.Array = data;
So my question is how to convert the string[] to double[,]?
Since you have a 2-d array, you'd need to iterate over each line and extract the values, then assign it into the proper position. You can use Select and double.Parse to convert the string values to double.
using (var reader = new StreamReader("file.txt"))
{
string line;
for (var count = 0; count < 4; ++count)
{
var data = reader.ReadLine()
.Split(',')
.Select(v => double.Parse(v))
.ToArray();
GlobalDataClass.Array[count,0] = data[0];
GlobalDataclass.Array[count,1] = data[1];
}
}
Now if your array was really double[][], then you could do something more like:
GlobalDataClass.Array = File.ReadAllLines("file.txt")
.Select(l => l.Split(',')
.Select(v => double.Parse(v))
.ToArray())
.ToArray();
Note: I think it's like a really bad idea to make it a global variable. There's probably a much better way to handle this.
I think that the best way is to use Array.ConvertAll.
Example:
string[] strs = new string[] { "1.00", "2.03" };
Array.ConvertAll(strs, Double.Parse);
System.IO.StreamReader file = new System.IO.StreamReader("c:\\test.txt");
int counter =0 ;
while((line = file.ReadLine()) != null)
{
var lineData= line.Split(',');
GlobalDataClass.Array[counter,0] = double.Parse(lineData[0]);
GlobalDataClass.Array[counter,1] = double.Parse(lineData[1]);
counter++;
}
Try This:
String [] words;
int lineCount=0;
String [] Lines=File.ReadAllLines(#"C:\Data.txt");
for (int i=0;i<Lines.Length;i++)
{
words = Lines[i].Split(',');
for (int j = 0; j < 2; j++)
{
GlobalDataClass.Array[i,j] = Convert.ToDouble(words[j].Trim());
}
}
I am using some part of your code to show you how you do this task.
int mCount = 0;
using (streamreader sr = new streamreader("file.txt")) {
string[] data = sr.ReadLine().Split(',');
GlobalDataClass.Array[mCount , 0] = Double.Parse(data[0]);
GlobalDataClass.Array[mCount , 1] = Double.Parse(data[1]);
mCount += 1;
}
double[] doubleArray = strArray.Select(s => Double.Parse(s)).ToArray();
int k = 0;
for (int i = GlobalDataClass.Array.GetLowerBound(0); i <= GlobalDataClass.Array.GetUpperBound(0); i++)
{
for (int j = GlobalDataClass.Array.GetLowerBound(1); j <= GlobalDataClass.Array.GetUpperBound(1); j++)
{
double d = doubleArray[k];
GlobalDataClass.Array.SetValue(d, i, j);
k++;
}
}
If the number of lines can vary:
var lines = File.ReadAllLines("file.txt");
var data = new double[lines.Length, 2];
for (var i = 0; i < lines.Length; i++)
{
var temp = lines[i].Split(',');
data[i,0] = double.Parse(temp[0]);
data[i,1] = double.Parse(temp[1]);
}
GlobalDataClass.Array = data;
..or, if the number of lines is a constant value:
using (var sr = new StreamReader("file.txt"))
{
var i = 0;
var len = GlobalDataClass.GetLength(0);
while (sr.Peak() >= 0 && i < len)
{
var temp = sr.ReadLine().Split(',');
GlobalDataClass.Array[i,0] = double.Parse(temp[0]);
GlobalDataClass.Array[i,1] = double.Parse(temp[1]);
i++;
}
}
I have a 2D array that I need to be able to convert to a string representation and back to array format. I would like to create a generci method that will handle any array 1d, 2d, 3d etc. so I can reuse the method in future.
What is the best way of going about this?
string[,] _array = new string[_helpTextItemNames.Count, 2];
If you do not care to much about the structure of the string then the SoapFormatter is an option. Here is a quick and dirty example. Not pretty but it might work for you.
public static class Helpers
{
public static string ObjectToString(Array ar)
{
using (MemoryStream ms = new MemoryStream())
{
SoapFormatter formatter = new SoapFormatter();
formatter.Serialize(ms, ar);
return Encoding.UTF8.GetString(ms.ToArray());
}
}
public static object ObjectFromString(string s)
{
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(s)))
{
SoapFormatter formatter = new SoapFormatter();
return formatter.Deserialize(ms) as Array;
}
}
public static T ObjectFromString<T>(string s)
{
return (T)Helpers.ObjectFromString(s);
}
}
These helpers can be used to transform any Serializable object to a string, including arrays, as long as the elements of the array are serializable.
// Serialize a 1 dimensional array to a string format
char[] ar = { '1', '2', '3' };
Console.WriteLine(Helpers.ObjectToString(ar));
// Serialize a 2 dimensional array to a string format
char[,] ar2 = {{ '1', '2', '3' },{ 'a', 'b', 'c' }};
Console.WriteLine(Helpers.ObjectToString(ar2));
// Deserialize an array from the string format
char[,] ar3 = Helpers.ObjectFromString(Helpers.ObjectToString(ar2)) as char[,];
char[,] ar4 = Helpers.ObjectFromString<char[,]>(Helpers.ObjectToString(ar2));
If you want to determain your own format, the hard part is just walking a rectangular array because Array.GetValue and Array.SetValue expect a specific form. Here is StringFromArray, I'll leave ArrayFromString as an exercise (it's just the reverse with a little parsing). Note that the code below only works on rectangular arrays. If you want to support jagged arrays, that's completely different, but at least much simpler. You can tell if an array is jagged by checking array.GetType() for Array. It also doesn't support arrays whos lower-bounds is anything other than zero. For C# that doesn't mean anything, but it does mean that it may not work as a general library to be used from other languages. This can be fixed, but it's not worth the price of admission IMO. [deleted explative about non-zero-based arrays]
The format used here is simple:
[num dimensions]:[length dimension #1]:[length dimension #2]:[...]:[[string length]:string value][[string length]:string value][...]
static string StringFromArray(Array array)
{
int rank = array.Rank;
int[] lengths = new int[rank];
StringBuilder sb = new StringBuilder();
sb.Append(array.Rank.ToString());
sb.Append(':');
for (int dimension = 0; dimension < rank; dimension++)
{
if (array.GetLowerBound(dimension) != 0)
throw new NotSupportedException("Only zero-indexed arrays are supported.");
int length = array.GetLength(dimension);
lengths[dimension] = length;
sb.Append(length);
sb.Append(':');
}
int[] indices = new int[rank];
bool notDone = true;
NextRank:
while (notDone)
{
notDone = false;
string valueString = (array.GetValue(indices) ?? String.Empty).ToString();
sb.Append(valueString.Length);
sb.Append(':');
sb.Append(valueString);
for (int j = rank - 1; j > -1; j--)
{
if (indices[j] < (lengths[j] - 1))
{
indices[j]++;
if (j < (rank - 1))
{
for (int m = j + 1; m < rank; m++)
indices[m] = 0;
}
notDone = true;
goto NextRank;
}
}
}
return sb.ToString();
}
As I know, you have a 2d array[n cols x n rows]. And you want convert it to string, and after that you'd like to convert this string back in to a 2d array. I have an idea as follow:
//The first method is convert matrix to string
private void Matrix_to_String()
{
String myStr = "";
Int numRow, numCol;//number of rows and columns of the Matrix
for (int i = 0; i < numRow; i++)
{
for (int j = 0; j < numCol; j++)
{
//In case you want display this string on a textbox in a form
//a b c d . . . .
//e f g h . . . .
//i j k l . . . .
//m n o p . . . .
//. . . . . . . .
textbox.Text = textbox.Text + " " + Matrix[i,j];
if ((j == numCol-1) && (i != numRow-1))
{
textbox.Text = textbox.Text + Environment.NewLine;
}
}
}
myStr = textbox.text;
myStr = myStr.Replace(" ", String.Empty);
myStr = myStr.Replace(Environment.NewLine,String.Empty);
}
//and the second method convert string back into 2d array
private void String_to_Matrix()
{
int currentPosition = 0;
Int numRow, numCol;//number of rows and columns of the Matrix
string Str2 = textbox.Text;
Str2 = Str2 .Replace(" ", string.Empty);
Str2 = Str2 .Replace(Environment.NewLine, string.Empty);
for (int k = 0; k < numRow && currentPosition < Str2 .Length; k++)
{
for (int l = 0; l < numCol && currentPosition < Str2 .Length; l++)
{
char chr = Str2 [currentPosition];
Matrix[k, l] = chr ;
currentPosition++;
}
}
}
Hope this help!