I am very new to c#. I am using Mono. I want to loop through each line in a TextView object and do my own processing to each line. I have narrowed it down to the Buffer property that contains a Text property but this property contains the whole text. How do I break it down into separate lines/strings?
string Line;
for (int i = 0;i < txtvMain.Buffer.LineCount; i++)
{
Line = txtvMain.Buffer.?;
}
(Untested) simple solution (perhaps not the most efficient):
string[] lines = txtvMain.Buffer.Text.split('\n');
Related
i'm having trouble reading in a text file which contains 9 sets of three integer values separated by commas. This is what i have done so far, but how would i be able to read through the data going down row one to get a max value?
very stuck with a program the data text file looks like
21,7,11
20,10,12
17,7,18
these represent temperature, height and carbon%
i have read in the file as so
{
string s;
System.IO.StreamReader inputFile = new System.IO.StreamReader(DataFile);
s = inputFile.ReadLine();
int noDataLines = int.Parse(s);
double[,] data = new double[noDataLines, 3];
string[] ss;
is this right if the data is stored in the debug folder as a .txt file?
from here how would i go about getting a max temp(ie only reading the first vertical column of data)?
We can simply use mixture of System.IO File.ReadLines() method and LINQ .ToList() in order to read all text lines to List<string>. At this point we can just iterate through the collection parsing double values from text lines :
List<string> lines = File.ReadLines("filepath").ToList();
List<int[]> values = new List<int[]>();
int[] temp = new int[3];
for (int i = 0; i < lines.Count; i++)
{
string[] strValues = lines[i].Split(',');
for (int i2 = 0; i2 < strValues.Length; i2++)
temp[i2] = Convert.ToInt32(strValues[i2]);
values.Add(temp.ToArray());
}
Or we can use LINQ :
List<string> lines = File.ReadLines("filepath").ToList();
List<int[]> values = new List<int[]>();
int[] temp = new int[3];
for (int i = 0; i < lines.Count; i++)
values.Add(lines[i].Split(',')
.Select(l => Convert.ToInt32(l)).ToArray());
Redirect me if this is already a previously solved issue!
In my program, I have a Stage in which the user can view a list of content, stored in a list consisting of Strings.
goToView.setOnAction(event ->{
menuStage.close();
viewStage.show();
String horseNameList = "";
for(int i = 0; i < accountList.size(); i++){
if(accountList.get(i).userName.equals(uName)){
for(int j = 0; j < accountList.get(i).createdHorses.size(); j++){
horseNameList += accountList.get(i).createdHorses.get(j);
horseNameList += "\n" + "\n";
}
}
Text hNameListTXT = new Text(horseNameList);
hNameListTXT.setFont(Font.font("Tahoma", FontWeight.NORMAL, 12));
listVbox.getChildren().add(hNameListTXT);
}
createdHorses is a List of Strings, listVbox is as you may think a VBox where the String (which converts to a Text) is printed. Now, when I close the Stage with the following EventHandler, nothing in particular happens:
backView.setOnAction(event -> {
viewStage.close();
menuStage.show();
});
But as I then open the Stage once again (by using another EventHandler similar to the one I use to close the first Stage with), my List (or String) har been doubled. What should I do to clear the String (or possibly the Text) so that it doesn't display it twice?
What should I do to clear the String (or possibly the Text) so that it
doesn't display it twice?
The VBox has a method getChildren() which returns an ObservableList. So you could use clear() on it to remove all the children.
my text file :
3.456 5.234 Saturday 4.15am
2.341 6.4556 Saturday 6.08am
At first line, I want to read 3.456 and 5.234 only.
At second line, I want to read 2.341 and 6.4556 only.
Same goes to following line if any.
Here's my code so far :
InputStream instream = openFileInput("myfilename.txt");
if (instream != null) {
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line=null;
while (( line = buffreader.readLine()) != null) {
}
}
Thanks for showing some effort. Try this
while (( line = buffreader.readLine()) != null) {
String[] parts = line.split(" ");
double x = Double.parseDouble(parts[0]);
double y = Double.parseDouble(parts[1]);
}
I typed this from memory, so there might be syntax errors.
int linenumber = 1;
while((line = buffreader.readLine()) != null){
String [] parts = line.split(Pattern.quote(" "));
System.out.println("Line "+linenumber+"-> First Double: "+parts[0]+" Second Double:"
+parts[1]);
linenumber++;
}
The code of Bilbert is almost right. You should use a Pattern and call quote() for the split. This removes all whitespace from the array. Your problem would be, that you have a whitespace after every split in your array if you do it without pattern. Also i added a Linenumber to my output, so you can see which line contains what. It should work fine
I have a tab-delimited text file of size of many GBs. Task here is to append header texts to each column. As of now, I use StreamReader to read line by line and append headers to each column. It takes a lot of time as of now. Is there a way to make it faster ? I was thinking if there is a way to process the file column-wise. One way would be to import the file in database table and then bcp out the data after appending the headers. Is there any other better way, probably by calling powershell, awk/sed in C# code ?
Code is as follows :
StreamReader sr = new StreamReader(#FilePath, System.Text.Encoding.Default);
string mainLine = sr.ReadLine();
string[] fileHeaders = mainLine.Split(new string[] { "\t" }, StringSplitOptions.None);
string newLine = "";
System.IO.StreamWriter outFileSw = new System.IO.StreamWriter(#outFile);
while (!sr.EndOfStream)
{
mainLine = sr.ReadLine();
string[] originalLine = mainLine.Split(new string[] { "\t" }, StringSplitOptions.None);
newLine = "";
for (int i = 0; i < fileHeaders.Length; i++)
{
if(fileHeaders[i].Trim() != "")
newLine = newLine + fileHeaders[i].Trim() + "=" + originalLine[i].Trim() + "&";
}
outFileSw.WriteLine(newLine.Remove(newLine.Length - 1));
}
Nothing else operating on just text files is going to be significantly faster - fundamentally you've got to read the whole of the input file, and you've got to create a whole new output file, as you can't "insert" text for each column.
Using a database would almost certainly be a better idea in general, but adding a column could still end up being a relatively slow business.
You can improve how you're dealing with each line, however. In this code:
for (int i = 0; i < fileHeaders.Length; i++)
{
if(fileHeaders[i].Trim() != "")
newLine = newLine + fileHeaders[i].Trim() + "=" + originalLine[i].Trim() + "&";
}
... you're using string concatenation in a loop, which will be slow if there's a large number of columns. Using a StringBuilder is very likely to be more efficient. Additionally, there's no need to call Trim() on every string in fileHeaders on every line. You can just work out which columns you want once, trim the header appropriately, and filter that way.
I've come across this several times in a couple years of programming so I decided to do some research to see if it was possible. Often I create data structures in code that are initialized in a table like manner, with rows and columns, and I would have liked to have this table-to-text feature for code readability. How can you create a table in word, or excel, or some other program, and output the cells of the table to text, with spaces (not tabs)? Word can do it with tabs, and excel can do it with misaligned spaces. Is there any program out there that automates this?
Have you tried using a monospace font, such as courier, when you export from excel? Most fonts will adjust spacing based on the specific width, height and kerning of each character but a monospace font will allow you to use spaces for alignment.
As for converting tabs to spaces automagically, there must be 100s if not 1000s of methods, apps, commands available out there.
I spent an hour or 2 researching this. I experimented with excel and word and they both came so close to exact solution that it made me crazy. I tried other programs online but with no luck. Here's my solution, Microsoft's Word's Table-To-Text feature and custom C# program that converts the Word-tabified text to column aligned text with spaces and not tabs.
1) Put your columns and rows in an MS Word Table
2) Convert table to text with tabs (look up how to do this)
3) Save the converted table to a plain text file
4) Use my program to open and convert the file
5) Copy the text in the output file to your code
Below is the C# Windows Form Application I wrote. I apologize for lack of optimization. I was at work and wanted it done as quickly as possible:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApplication1
{
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
OpenFileDialog of = new OpenFileDialog();
of.Title = "Select Tabbed Text File To Convert";
if (of.ShowDialog() != DialogResult.OK)
return;
StreamReader s = new StreamReader(of.OpenFile());
List<string> lines = new List<string>();
string line;
// Get each line into an array of lines.
while ((line = s .ReadLine()) != null)
lines.Add(line);
int numTabs = 0;
// count the number of tabs in each line, assume good input, i.e.
// all lines have equal number of tabs.
foreach (char c in lines[0])
if (c == '\t')
numTabs++;
for (int i = 0; i < numTabs; i++)
{
int tabIndex = 0;
// Loop through each line and find the "deepest" location of
// the first tab.
foreach (string l in lines)
{
int index = 0;
foreach (char c in l)
{
if (c == '\t')
{
if (index > tabIndex)
tabIndex = index;
break;
}
index++;
}
}
// We know where the deepest tab is, now we go through and
// add enough spaces to take the first tab of each line out
// to the deepest.
//foreach (string l in lines)
for (int l = 0; l < lines.Count; l++)
{
int index = 0;
foreach (char c in lines[l])
{
if (c == '\t')
{
int numSpaces = (tabIndex - index) + 1;
string spaces = "";
for (int j = 0; j < numSpaces; j++)
spaces = spaces + " ";
lines[l] = lines[l].Remove(index, 1);
lines[l] = lines[l].Insert(index, spaces);
break;
}
index++;
}
}
}
FileInfo f = new FileInfo(of.FileName);
string outputFile = f.FullName.Insert(f.FullName.IndexOf(f.Extension), " (Aligned)");
StreamWriter w = new StreamWriter(outputFile);
foreach (string l in lines)
w.Write(l + "\r\n");
w.Close();
s.Close();
MessageBox.Show("Created the file: " + outputFile);
}
}
}