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());
Related
country residents area capital
Andorra 71201 468 Andorra la Vella
Italien 58133509 301230 Rom
San Marino 29251 61 San Marino
I need to store the information (capital, residents, area, capital) in different variables. How would I go about parsing this? Notice that sometimes there are spaces in the names.
I have tried reading each token ( scanner.next() ) this fails when there are spaces in the capital or country name.
I have tried reading each line and then parsing it but I can't figure out a way to parse everything correctly since there are sometime spaces in the names. (I used indexOf() and substring() )
This is part of a bigger file but there are no spaces in the residents or area field in the entire field.
My try:
while(scanner.hasNext()){
String info = scanner.nextLine();
//parse string
int nameindex = info.indexOf(" ");
System.out.println(info.substring(0,nameindex));
int resindex = info.indexOf(" ", nameindex);
}
I hope you have a multiline string as per your question title. So why don't you simply use a regex for the whole content. Given the string is stored in the variable data
data.split("[ ]{2,}")
This would give the array of data as a whole. So when you have to parse it you can simply do a loop 4 elements at a time
(edit)
or else you can simply use this function... hope this will be easier for you.
List<Map<String, String>> parse(String data){
List<Map<String, String>> dataList = new ArrayList<Map<String, String>>();
String[] lines = data.split("\n");
String[] keys = lines[0].split("[ ]{2,}");
for (int i = 1; i < lines.length; i++) {
String row[] = lines[i].split("[ ]{2,}");
Map<String, String> rowMap = new HashMap<String, String>();
for (int j = 0; j < row.length; j++) {
rowMap.put(keys[j], row[j]);
}
dataList.add(rowMap);
}
return dataList;
}
I have a text file that consist of
name,definition;
name1,definition;
name2, definition;
i know how to split the the string that is being taken into the script from the text file but i dont know how to get it all into a 2darray or jagged array.
it should look like this after words
array[0][0] = name;
array[0][1] = definition;
SORRY, i forgot to say what language, its in C#
Here's your solution in JavaScript. note If your row values can contain quotes, new lines, or escaped delimiters more parsing is necessary.
http://jsfiddle.net/N4YYA/
var result = [];
var txt = document.getElementById("test").value;
// get lines
var lines = txt.split(";");
for(var i=0; i<lines.length; i++) {
// get and trim whitespace off the line
var line = lines[i].replace(/(^[\s\r\n]*|[\s\r\n]*$)/g, "");
var values = line.split(",");
var row = [];
for(var j=0; j<values.length; j++) {
// get and trim whitespace off each value
var value = values[j].replace(/(^[\s\r\n]*|[\s\r\n]*$)/g, "");
// add it to your row array
row.push(value);
}
// add row to results
result.push(row);
}
// debug show result
var o = document.getElementById("outp");
for(var x=0; x<result.length; x++)
o.innerHTML += result[x].toString() + "<br/>";
In C#:
string[][] array = inputString.Split(';').Select(x => x.Split(',')).ToArray();
and if you want to include the trim for some reason:
string[][] array = inputString.Split(';').Select(x => x.Split(',').Select(y=>y.Trim()).ToArray()).ToArray();
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');
I have the code:
String s = "a,b,c,d,e";
int[] i = s.split(",");
but this cast is not avaiable.
Some one can help me?
Thanks
You must loop over each element in the array and cast them one by one.
Like this:
String s = "a,b,c,d,e";
String[] strings = s.split(",");
int[] i = new int[strings.length];
for(int j = 0; j < strings.length; j++)
{
i[j] = Integer.parseInt(strings[j]);
}
Note that this code will crash, since the elements in the string-array aren't integers.
Java is strongly-typed which means it won't allow you to cast between incompatible types. In order to convert between integers and strings, you need to explicitly do the conversion. Integer.parseInt can convert a string to an integer. So you will need to loop through your array and convert each integer to a string individually.
String[] strings = "a,b,c,d,e".split(",");
int parsedIntegers[] = new int[strings.length];
for (int i = 0; i < strings.length; i++) {
parsedIntegers[i] = Integer.parseInt(strings[i]);
}
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);
}
}
}