I am having a problem with the following:
I am loading a file into C# and then I am splitting it by lines with this code.
// Splitting by line from original file
string[] lines = showText.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
Now I need a for loop that will go through lines and get Substring from those lines, separately.
Here is what I am trying to accomplish, in a way:
for (int i = 0; i < lines.Length; i++)
{
int[] testing = new int[i];
testing[i] = int.Parse(lines[i].Substring(16, 1));
textBox1.Text = testing.ToString();
}
The error here is: Index was outside the bounds of the array.
Here is a picture also to get better idea as to what I'm trying to do.
http://s30.postimg.org/jbmjmqv1t/work.jpg
textBox1.Text = lines[0].Substring(16,1) + " " + lines[0].Substring(23,9);
textBox1.Text = lines[1].Substring(16,1) + " " + lines[1].Substring(23,9); //etc
Could anyone help me with this?
You are creating the array in the for loop, so it is being created for each line and with the wrong length. Instead of this part of the code:
for (int i = 0; i < lines.Length; i++)
{
int[] testing = new int[i];
testing[i] = int.Parse(lines[i].Substring(16, 1));
textBox1.Text = testing.ToString();
}
you should be doing this:
int[] testing = new int[lines.Length];
for (int i = 0; i < lines.Length; i++)
{
testing[i] = int.Parse(lines[i].Substring(16, 1));
textBox1.Text = testing.ToString();
}
This is how I've solved it.
int[] testing = new int[lines.Length];
textBox1.Clear(); //Just to clear it if button pressed again
for (int i = 0; i < lines.Length; i++)
{
testing[i] = int.Parse(lines[i].Substring(16, 1));//just getting the needed value
textBox1.Text += testing[i].ToString() + "\r\n" ;//adding each value to textBox1, separated by new line
}
Related
I am trying to make an array that will gather all the lines in all the files in a directory, I thought I had it finally, but when the string array gets to entry 111 it crashes with an IndexOutOfRangeException
string[] WordList = new string[AdjectiveListLength];
Console.WriteLine("Length .. " + AdjectiveListLength);
Console.WriteLine("String Length .. " + WordList.Length);
int o = 0;
for (int i = 0; i < FileEntries.Length; i++)
{
WordList = File.ReadAllLines(FileEntries[i]);
foreach (string s in WordList)
{
Console.WriteLine(s + " .. " + i + " .. " + o);
WordList[o] = s;
//o += 1;
}
}
The exception points to the int I commented out when I get the error, I've been trying to get this for a few hours and I've finally gotten this far I feel like I'm 1 inch from the finish line but I can't figure out what's going on.
The best way for this task is to use a List<string> that could be used without knowing beforehand the length of each file in your FileEntries array
List<string> WordList = null;
for (int i = 0; i < FileEntries.Length; i++)
{
WordList = File.ReadLines(FileEntries[i]).ToList();
foreach (string s in WordList)
Console.WriteLine(s + " .. " + i);
// If you want also the line number then you could just use normal for..loop and C# 6.0 syntax
for(int o = 0; o < WordList.Count(); o++)
Console.WriteLine($"File:{i} at line {o} is ..{WordList[o]}");
}
If you really want to use arrays then you don't need to dimension the array because File.ReadAllLines already creates the array for you
string[] WordList = null;
for (int i = 0; i < FileEntries.Length; i++)
{
WordList = File.ReadAllLines(FileEntries[i]);
foreach (string s in WordList)
Console.WriteLine(s + " .. " + i);
}
case 8:
string[][] Ws1Data = new[]
{
File.ReadAllLines(#"\university\Assignment2Alg\files\YearSorted.txt"),
File.ReadAllLines(#"\university\Assignment2Alg\files\MonthSorted.txt"),
File.ReadAllLines(#"\university\Assignment2Alg\files\WS1_AFSorted.txt"),
File.ReadAllLines(#"\university\Assignment2Alg\files\WS1_RainSorted.txt"),
File.ReadAllLines(#"\university\Assignment2Alg\files\WS1_SunSorted.txt"),
File.ReadAllLines(#"\university\Assignment2Alg\files\WS1_TMaxSorted.txt"),
File.ReadAllLines(#"\university\Assignment2Alg\files\WS1_TMinSorted.txt"),
};
for (int i = 0; i < Ws1Data.Length; i++)
{
string[] innerArray = Ws1Data[i];
for (int a = 0; a < innerArray.Length; a++)
{
Console.WriteLine(innerArray[a] + " ");
}
Console.WriteLine();
}
break;
As you can see I have an array of text files which all have data inside them, I want the data to be showed in the format of columns and not below each other.
So it shows like this.
1920 january 20.2
1923 february 21.0
instead of this
1920
1923
january
february
20.2
24.2
Im stuck and cant find out how to do it, Probably really easy once its pointed out, but you dont learn if you dont ask.
Do your files have the same number of lines?
If so, something like this should work:
int nRows = Ws1Data[0].Length;
int nColumns = Ws1Data.Length;
string tempString = "";
for (int i = 0; i < nRows; i++)
{
tempString = "";
for (int j = 0; j < nColumns; j++)
{
tempString = tempString + Ws1Data[j][i];
tempString = tempString + " ";
}
Console.WriteLine(tempString);
}
Depending on the number of columns, you can have a stack overflow due to tempString. If so, just allocate the size statically
I have a 2D array of floats and I want to convert it into 1D array of strings, where each string is one row of elements from 2D array. I am not getting output in text file as I expected. Can anyone tell me what I'm doing wrong? It will be great help to me, if somebody could provide efficient code with corrections.
string[] set = new string[240];
string value = "#"
for (int i = 0; i < 240; i++)
{
for (int j = 0; j < 320; j++)
{
value = Convert.ToString(ImageArray[i, j]);
value += ",";
}
set[i] = value + Environment.NewLine;
value = " ";
}
for(int k=0;k<240;k++)
{
System.IO.File.AppendAllText(#"C:\Users\mtech\Desktop\sathya.txt", set[k]);
textBlock1.Text = set[k];
value = " ";
}
inside your inner for loop(j), you are overwriting the value of value variable.
i.e.
for (int j = 0; j < 320; j++)
{
value = Convert.ToString(ImageArray[i, j]);
value += ",";
}
instead of above, you should be doing:
for (int j = 0; j < 320; j++)
{
value += Convert.ToString(ImageArray[i, j]) +",";
}
also, you don't need to perform two nested loops for this task, take a look at String.Join
Here is the shorter way with LINQ:
var allValues = ImageArray.OfType<float>();
string[] lines = new string[240];
for(int i=0; i<240; i++)
{
lines[i] = string.Join(",", allValues.Skip(i*320).Take(320));
}
File.AppendAllLines(#"C:\Users\mtech\Desktop\sathya.txt", lines);
You're re-assigning value in every iteration in your nested for loop. Use the += operator, instead. Another thing you should consider is the use of StringBuilder if you're going to repeatedly append to a string. strings are immutable so you're actually creating a new string every time you append to it.
Not sure if this applies to your case (because of the boundaries in your for loops), but you can use LINQ to flatten a multidimensional array. Example:
float[,] arr = new float[2,2]
{
{123.48F, 45.3F},
{954.23F, 91.3F}
};
var str = string.Join("",
arr.Cast<float>()
.Select(x => Convert.ToString(x) + ","));
I am building two arrays in c# and pass them to a js function like this:
//call js to show the map with the markers
string[] lats = new string[10];
string[] longs = new string[10];
for (int i = 0; i < 10; i++)
{
lats[i] = dv[i]["Latitude"].ToString();
}
for (int i = 0; i < 10; i++)
{
longs[i] = dv[i]["Longitude"].ToString();
}
StringBuilder sbLats = new StringBuilder();
string[] latsArray = lats.ToArray<string>();
//Build the JS array.
sbLats.Append("[");
for (int i = 0; i < latsArray.Length; i++)
{
sbLats.AppendFormat("'{0}', ", latsArray[i]);
}
sbLats.Append("]");
StringBuilder sbLongs = new StringBuilder();
string[] longsArray = longs.ToArray<string>();
//Build the JS array.
sbLongs.Append("[");
for (int i = 0; i < longs.Length; i++)
{
sbLongs.AppendFormat("'{0}', ", longsArray[i]);
}
sbLongs.Append("]");
ScriptManager.RegisterStartupScript(this, this.GetType(), "mapMarket", "buildMapWithMarkers('map_market', " + latsArray + ", " + longsArray + ", " + "false" + ");", true);
For some unknown reason this throws an exception here (in the aspx page, part of generated js):
buildMapWithMarkers('map_market', System.String[], System.String[], false)
which says:
Uncaught SyntaxError: Unexpected token ]
Can you please tell me where I am wrong?
Solved it using #Skilwz suggestion (JavaScriptSerializer):
//call js to show the map with the markers
string[] lats = new string[10];
string[] longs = new string[10];
for (int i = 0; i < 10; i++)
{
lats[i] = dv[i]["Latitude"].ToString();
}
for (int i = 0; i < 10; i++)
{
longs[i] = dv[i]["Longitude"].ToString();
}
string serializedLat = (new JavaScriptSerializer()).Serialize(lats);
string serializedLong = (new JavaScriptSerializer()).Serialize(longs);
ScriptManager.RegisterStartupScript(this, this.GetType(), "mapMarket", "buildMapWithMarkers('map_market', " + serializedLat + ", " + serializedLong + ", " + "false" + ");", true);
I have tried several time but couldn’t find the way to solve my problem. Here my txt file shown in below.
695
748
555
695
748
852
639
748
I put the for loop to read the data and put them in to array. So now I want to filter repeat numbers from the input txt data. How can I have a count of repeated data.
static void Main(string[] args)
{
int x = 0;
int count = 0;
String[] line = File.ReadAllLines("C:/num.txt");
int n = line.Length;
String[] res = new String[n];
for (int i = 0; i < n; i++)
{
res[i] = line[i].Substring(x,x+8);
Console.WriteLine(res[i]);
}
Console.ReadLine();
}
You use GroupBy()
var result = res.GroupBy(x => x);
foreach(var g in result)
{
Console.WriteLine(g.Key + " count: " + g.Count());
}
Somehow you have to keep track of things you have seen before.
One way to do that is to place the numbers in a list the first time you see them. If a given number is already in the list, filter it out on the latter occurrences.
Here's an example with the list. Note that your code to fetch a substring of the input crashes.
static void Main(string[] args)
{
int x = 0;
int count = 0;
String[] line = new string[] { "123", "456", "123" }; //File.ReadAllLines("C:/num.txt");
int n = line.Length;
String[] res = new String[n];
List<string> observedValues = new List<string>();
for (int i = 0; i < n; i++)
{
string consider = line[i]; // This code crashes: .Substring(x, x + 8);
if (!observedValues.Contains(consider))
{
observedValues.Add(consider);
res[i] = consider;
Console.WriteLine(res[i]);
}
else
{
Console.WriteLine("Skipped value: " + consider + " on line " + i);
}
Console.ReadLine();
}
}
Another method is to pre-sort the input so that duplicates are adjacent.
Example:
(Note, you may want to remove white space in the input prior to sorting. Leading white space will break this code).
static void Main(string[] args)
{
int x = 0;
int count = 0;
String[] line = new string[] { "123", "456", "123" }; //File.ReadAllLines("C:/num.txt");
int n = line.Length;
String[] res = new String[n];
string previous = null;
Array.Sort(line); // Ensures that equal values are adjacent
for (int i = 0; i < n; i++)
{
string consider = line[i].Trim(); // Note leading whitespace will break this.
if (consider != previous)
{
previous = consider;
res[i] = consider;
Console.WriteLine(res[i]);
}
else
{
Console.WriteLine("Skipped value: " + consider + " on line " + i);
}
Console.ReadLine();
}
}
So now I want to filter repeat numbers from the input txt data.
if all you need is filter out duplicates you can use this:
String[] line = File.ReadAllLines("C:/num.txt");
var filteredLines = line.Distinct();
foreach (var item in filteredLines)
Console.WriteLine(item);