I'm solving a problem, which gets an array of strings from a .txt file, which contains the first and last name of a person. The problem is that when I try to split the elements from the string "line" and try to give other two strings those values, it doesn't work.
The text file contains:
Noah Mason
Emma Williams
Richard Daniel
and so on...
I want to split the lines into two separate string arrays "firstName" and "secondName". And I want something like this:
firstName[0]="Noah";
firstName[1]="Emma";
firstName[2]="Richard";
secondName[0]="Mason";
secondName[1]="Williams";
secondName[2]="Daniel";
To read text from text file and storing the data in array you can follow this approach
try (BufferedReader br = new BufferedReader(new FileReader(file))) { String line; while ((line = br.readLine()) != null) { String[] name = line.split(" ");
//Save the name array in any global array variable.} }
Related
my application basically reads a CSV file which will always have the same format and I need to application to create a CSV file with different formatting. Reading and writing CSV file is not the issue, however the problem I am having is reading from the string array containing all the data from the CSV file.
For example: From the below, how can I get the system to get me the 4th value only: Value Date
[0] = "\"Book Date\",\"Reference\",\"Descript\",\"Value Date\",\"Debit\",\"Credit\",\"Closing Balance\""
This is how I am reading from CSV file.
openFileDialog1.ShowDialog();
var reader = new StreamReader(File.OpenRead(openFileDialog1.FileName));
List<string> searchList = new List<string>();
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
searchList.Add(line);
}
Use String.Split. It returns a string array that contains the substrings in this instance that are delimited by elements of a specified string or Unicode character array.
var splitStrings = line.Split(",");
if (splitStrings.Length > 4)
{
searchList.Add(splitStrings[3]);
}
split the line and get the 4th value like this:
searchList.Add(line.Split(',')[3]);
I have a text file and I need to save specific items by type. So the numbers I have to save as integers and specific words as strings.
This is what I have so far:
string line;
int sizeOne;
int sizeTwo;
StreamReader file = new StreamReader(#"C:\Users\Asus\Documents\text.txt");
while ((line = file.ReadLine()) != null)
{
Console.WriteLine(line);
}
file.Close();
Console.ReadKey();
The .txt file is:
[header]
name = "Simple Maze"
size = 9,10
[/header]
[level]
xxxxxxxxx
x..xsx..x
x.xx.xx.x
x.......x
x..x.x..x
x..xxx..x
x.......x
x.xx.xx.x
x.x.t.x.x
xxxxxxxxx
[/level]
Since you are looping through the lines you can check at each line whether it Contains a certain string.
If you have found this line then you can twist the values that you need by using the String.Split method
If you have carved the values out of the file then you should Convert them to integer.
This is basically the algorithm in words. Now it's up to you to mould it into code.
You can find examples to each of the steps here on StackOverflow. Have fun
So I have a text file with information in the following format, with the name, email, and phone number.
Bill Molan, Bill.Molan#gmail.com, 612-789-7538
Greg Hanson, Greg.Hanson#gmail.com, 651-368-4558
Zoe Hall, Zoe.Hall#gmail.com, 952-778-4322
Henry Sinn, Henry.Sinn#gmail.com, 651-788-9634
Brittany Hudson, Brittany.Hudson#gmail.com, 612-756-4486
When my program starts, I want to read this file and make each row into a new Person(), which I will eventually add to a list. I am wanting to read each line, and then use the comma to separate each string to put into the constructor of Person(), which is a basic class:
public PersonEntry(string n, string e, string p)
{
Name = n;
Email = e;
Phone = p;
}
I have done some looking and I think that using a streamreader is going to work for reading the text file, but I'm not really sure where to go from here.
You can use the following method:
string line;
List listOfPersons=new List();
// Read the file and display it line by line.
System.IO.StreamReader file =
new System.IO.StreamReader(#"c:\yourFile.txt");
while((line = file.ReadLine()) != null)
{
string[] words = line.Split(',');
listOfPersons.Add(new Person(words[0],words[1],words[2]));
}
file.Close();
Assuming that the comma will never appear within the data:
Use StreamReader.ReadLine to read each line of text. With each line of text, use string.Split to split the line into an array of strings using the comma as the split character. Now you have an array of 3 strings where [0] is the name, [1] the email, and [2] the phone.
You can read all lines as below // assuming all lines will have 3 values always
var allLines = File.ReadAllLines(path);
var listOfPersons = new List<Person>();
foreach(var line in allLines)
{
var splittedLines = line.Split(new[] {","})
if(splittedLines!=null && splittedLines.Any())
{
listOfPersons.Add( new Person {
Name = splittedLines[0],
Email = splittedLines .Length > 1 ?splittedLines[1]:null,
Phone = splittedLines .Length > 2? splittedLines[2]:null,
});
}
}
this code is a sample must be checked for various conditions like array length etc also please check the
I'm making a simple text adventure in C# and I was wondering if it was possible to read certain lines from a .txt file and assign them to a string.
I am aware of how to read all the text from a .txt file but how exactly would I assign the contents of certain lines to a string?
Have you considered the ReadAllLines method?
It returns an array of lines from which you can choose your desired line.
So for eg, if you wish to choose the 3rd line (Assuming you have 3 lines in the file):
string[] lines = File.ReadAllLines(path);
string myThirdLine= lines[2];
Probably the easiest (and cheapest in terms of memory consumption) is File.ReadLines:
String stringAtLine10 = File.ReadLines(path).ElementAtOrDefault(9);
Note that it is null if there are less than 10 lines in the file. See: ElementAtOrDefault.
It's just the concise version of a StreamReader and a counter variable which increases on every line.
As an advanced alternative: ReadLines plus some LINQ:
var lines = File.ReadLines(myFilePath).Where(MyCondition).ToArray();
where MyCondition:
bool MyCondition(string line)
{
if (line == "something")
{
return true;
}
return false;
}
In case you don't want to load all lines atonce
using(StreamReader reader=new StreamReader(path))
{
String line;
while((line=reader.ReadLine())!=null)//process temp
}
Here's a example how you can assign the lines to a string, you can't decide which line is which via fields, you have to select them yourself.
which is the line of the string you want to assign.
For example, you want line one, you define which as one and not zero, you want line eight, you define which with eight.
string getWord(int which)
{
string readed = "";
using (Systen.IO.StreamReader read = new System.IO.StreamReader("PATH HERE"))
{
readed = read.ReadToEnd();
}
string[] toReturn = readed.Split('\n');
return toReturn[which - 1];
}
I have a text file which contains following
Name address phone salary
Jack Boston 923-433-666 10000
all the fields are delimited by the spaces.
I am trying to write a C# program, this program should read a this text file and then store it in the formatted array.
My Array is as follows:
address
salary
When ever I am trying to look in google I get is how to read and write a text file in C#.
Thank you very much for your time.
You can use File.ReadAllLines method to load the file into an array. You can then use a for loop to loop through the lines, and the string type's Split method to separate each line into another array, and store the values in your formatted array.
Something like:
static void Main(string[] args)
{
var lines = File.ReadAllLines("filename.txt");
for (int i = 0; i < lines.Length; i++)
{
var fields = lines[i].Split(' ');
}
}
Do not reinvent the wheel. Can use for example fast csv reader where you can specify a delimeter you need.
There are plenty others on internet like that, just search and pick that one which fits your needs.
This answer assumes you don't know how much whitespace is between each string in a given line.
// Method to split a line into a string array separated by whitespace
private string[] Splitter(string input)
{
return Regex.Split(intput, #"\W+");
}
// Another code snippet to read the file and break the lines into arrays
// of strings and store the arrays in a list.
List<String[]> arrayList = new List<String[]>();
using (FileStream fStream = File.OpenRead(#"C:\SomeDirectory\SomeFile.txt"))
{
using(TextReader reader = new StreamReader(fStream))
{
string line = "";
while(!String.IsNullOrEmpty(line = reader.ReadLine()))
{
arrayList.Add(Splitter(line));
}
}
}