TextFile to Dictionary - c#

I have different input text files i need to parse them to dictionary .
The first line contains an integer, N, denoting the number of entries in the phone book.
Each of the N subsequent lines describes an entry in the form of 22 space-separated values on a single line. The first value is a friend's namename, and the second value is an 88-digit phone numberphone number.
After the N lines of phone book entries, there are an unknown number of lines of queries. Each line (query) contains a namename to look up, and you must continue reading lines until there is no more input.
Note: Names consist of lowercase English letters and are first names only.
Here are some sample inputs files .
Sample 1:
3 // total three entries
john
34087423764 //8 digit phone number
abc
34087423123 //8 digit phone number
dce
24589756
dce
abc
three
Sample 2:
100000
mued 40502760
reiw 53841370
gkry 12304153
clrb 52664724
rbrq
xxxx
nlvk
qfrw
negg
Now i wrote a program to handle it but i dont know how to handle sample 2 and how to identify the queries any ideas how to handle first line then other samples
Dictionary<String, long> phoneNumber = new Dictionary<string, long>();
int counter = 0;
int N = 0;
//Reading Input Sample Text File
String filePath = #"c:\TextFiles\textInput.txt";
String QueryFilePath= #"c:\TextFiles\Queries.txt";
if (File.Exists(filePath))
{
StreamReader sreamReader = new StreamReader(filePath);
string line = string.Empty;
long key = 0;
string value = string.Empty;
while ((line = sreamReader.ReadLine()) != null)
{
//value = Regex.Match(line, "\\d+").Value;
key = Convert.ToInt64(Regex.Match(line, "\\d+").Value);
value = (Regex.Match(line, "\\D+").Value).TrimStart(',');
phoneNumber.Add(Convert.ToString(value), Convert.ToInt64(key));
}
sreamReader.Close();
if (File.Exists(QueryFilePath))
{
StreamReader queryFileStreatReader = new StreamReader(QueryFilePath);
string lines = string.Empty;
string values = string.Empty;
while ((lines = queryFileStreatReader.ReadLine()) != null)
{
values = (Regex.Match(lines, "\\D+").Value).TrimStart(',');
if (phoneNumber.ContainsKey(values) == true)
{
Console.WriteLine("{0}={1}", values, phoneNumber[values]);
}
else
{
Console.WriteLine("Not found");
}
}
queryFileStreatReader.Close();
}
}
Console.ReadKey();

Finally i solved this problem infect it was not well described in problem statement created a lot of confusion .
class Solution {
public static Dictionary<String, string> phoneBook = new Dictionary<string, string>();
static void Main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution */
//string searchText = "sam";
Int32 N = Convert.ToInt32(Console.ReadLine());
string readData = "";
for (Int32 i = 0; i < N; i ++)
{
readData = Console.ReadLine();
if (readData.Trim().Contains(" "))
if (!phoneBook.ContainsKey(readData.Trim().Split(' ')[0]))
phoneBook.Add(readData.Trim().Split(' ')[0], readData.Trim().Split(' ')[1]);
}
while ((readData = Console.ReadLine()) != null)
SearchPhoneNumbers(readData.Trim());
}
public static void SearchPhoneNumbers(string searchQuery)
{
if (phoneBook.ContainsKey(searchQuery))
Console.WriteLine("{0}={1}", searchQuery, phoneBook[searchQuery]);
else
Console.WriteLine("Not found");
}
}

Related

How to assign lines from a text file to different kind of variables

Had some trouble with reading and then storing the lines from a text file.
Need to make a map program, where the user can make a plan how to travel from A-B with metros. I need to store the names of the metro stations and the number of metro stations per line.
The format is: (where number is the number of station per line and text is the name of the stations
3
abc
dba
efg
2
asd
dfdf
5
sad
dff
asf
dgh
dfgh
So when a number appear it's a new line.
I already tried .split(\n) but this only works if I want to store all the lines in string. But the goal is to store the numbers in int and store the names in string.
Try following :
const string FILENAME = #"c:\temp\test.txt";
static void Main(string[] args)
{
StreamReader reader = new StreamReader(FILENAME);
List<List<string>> stationNames = new List<List<string>>();
List<string> lineNames = null;
string line = "";
int count = 0;
while ((line = reader.ReadLine()) != null)
{
if (count == 0)
{
count = int.Parse(line);
lineNames = new List<string>();
stationNames.Add(lineNames);
}
else
{
lineNames.Add(line.Trim());
count--;
}
}
}

Read lines of data from CSV then display data

I have to read info from a txt file, store it in a manner (array or list), then display the data. Program must include at least one additional class.
I've hit a wall and can't progress.
string, string, double, string
name,badge,salary,position
name,badge,salary,position
name,badge,salary,position
I'm sorry and I know the code below is disastrous but I'm at a loss and am running out of time.
namespace Employees
{
class Program
{
static void Main()
{
IndividualInfo collect = new IndividualInfo();
greeting();
collect.ReadInfo();
next();
for (int i = 0; i < 5; i++)
{
displayInfo(i);
}
exit();
void greeting()
{
Console.WriteLine("\nWelcome to the Software Development Company\n");
}
void next()
{
Console.WriteLine("\n*Press enter key to display information . . . *");
Console.Read();
}
void displayInfo(int i)
{
Console.WriteLine($"\nSoftware Developer {i + 1} Information:");
Console.WriteLine($"\nName:\t\t\t{collect.nameList[i]}");
}
void exit()
{
Console.WriteLine("\n\n*Press enter key to exit . . . *");
Console.Read();
Console.Read();
}
}
}
}
class IndividualInfo
{
public string Name { get; set; }
//public string Badge{ get; set; }
//public string Position{ get; set; }
//public string Salary{ get; set; }
public void ReadInfo()
{
int i = 0;
string inputLine;
string[] eachLine = new string[4];
string[,] info = new string[5, 4]; // 5 developers, 4x info each
StreamReader file = new StreamReader("data.txt");
while ((inputLine = file.ReadLine()) != null)
{
eachLine = inputLine.Split(',');
for (int x = 0; x < 5; x++)
{
eachLine[x] = info[i, x];
x++;
}
i++;
}
string name = info[i, 0];
string badge = info[i, 1];
string position = info[i, 2];
double salary = Double.Parse(info[i, 3]);
}
public List<string> nameList = new List<string>();
}
So far I think I can collect it with a two-dimensional array, but a List(s) would be better. Also, the code I've posted up there won't run because I can't yet figure out a way to get it to display. Which is why I'm here.
using System.IO;
static void Main(string[] args)
{
using(var reader = new StreamReader(#"C:\test.csv"))
{
List<string> listA = new List<string>();
List<string> listB = new List<string>();
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(';');
listA.Add(values[0]);
listB.Add(values[1]);
}
}
}
https://www.rfc-editor.org/rfc/rfc4180
or
using Microsoft.VisualBasic.FileIO;
var path = #"C:\Person.csv"; // Habeeb, "Dubai Media City, Dubai"
using (TextFieldParser csvParser = new TextFieldParser(path))
{
csvParser.CommentTokens = new string[] { "#" };
csvParser.SetDelimiters(new string[] { "," });
csvParser.HasFieldsEnclosedInQuotes = true;
// Skip the row with the column names
csvParser.ReadLine();
while (!csvParser.EndOfData)
{
// Read current line fields, pointer moves to the next line.
string[] fields = csvParser.ReadFields();
string Name = fields[0];
string Address = fields[1];
}
}
http://codeskaters.blogspot.ae/2015/11/c-easiest-csv-parser-built-in-net.html
or
LINQ way:
var lines = File.ReadAllLines("test.txt").Select(a => a.Split(';'));
var csv = from line in lines
select (from piece in line
select piece);
^^Wrong - Edit by Nick
It appears the original answerer was attempting to populate csv with a 2 dimensional array - an array containing arrays. Each item in the first array contains an array representing that line number with each item in the nested array containing the data for that specific column.
var csv = from line in lines
select (line.Split(',')).ToArray();
This question was fully addressed here:
Reading CSV file and storing values into an array

How to display a string up until a certain special character in a textbox from a file

I would want to know how do I display strings from a textfile in a textbox but only untill it reaches a '#" sign in the textfile in c# ?
string lines = outputToBox.ReadToEnd();
//outputToBox is streamreader var that holds the conent of the file
int index = lines.IndexOf('#');
txtDisplay.Text = lines.Substring(0, index);
The problem I now have is that it does not display all the lines in the textbox only the first one
It would help if you included an example of what you have and what you want it to look like. I assume your input looks something like this
x.field1#x.field2#x.field3
y.field1#y.field2#y.field3
z.field1#z.field2#z.field3
If there are multiple lines in the textbox you could turn it into an array and then run foreach through them (if you need an example I can show you)
string[] fileInput = System.IO.File.ReadAllLines(#FILE_PATH)
it would output like this
fileInput[0] = x.field1#x.field2#x.field3
then you can add
string[] myArray = fileInput[x].Split('#') // Into an array, so if you only want 'x.field1', you enter fileInput[0], and return myArray[0]
and implement your foreach. If you want very specific fields from the file that start with certain chars I recommend reading a bit about LINQ and how run small queries.
if your goal is to do this for every existing instance of a string in whatever file, you need a loop.
https://msdn.microsoft.com/en-us/library/bb308959.aspx (LINQ)
This should do the trick and is probably the optimal solution, without more information >:D.
void Main()
{
Debug.Print(Homework_Problem_Number_54_000_601.
Parse("NAME SURNAME NUMBER #2131231313"));
//this prints "NAME SURNAME NUMBER " without the quotes to the console
}
void SetTextBoxText(TextBox textBox, string value) { textBox.Text = value; }
unsafe static class Homework_Problem_Number_54_000_601
{
[ThreadStatic]static StringBuilder __builder;
public static string Parse(string textToParse)
{
if (textToParse == null) return null;
var builder = __builder = __builder ?? new StringBuilder();
builder.clear();
fixed (char* pTextToParse = textToParse)
{
var pTerminus = pTextToParse + textToParse.Length;
for (var pChar = pTextToParse; pChar < pTerminus; ++pChar)
{
switch (*pChar)
{
case '#':
return builder.ToString();
break;
default:
builder.Append(*pChar);
break;
}
}
}
throw new ArgumentException("textToParse was not in the expected format");
}
}
As for reading from the file, that's hard to say without a file format specification from you, but now that you have posted code I'd try this:
string lines = outputToBox.ReadToEnd();
StringBuilder builder = new StringBuilder();
foreach (string line in lines.Split('\n'))
{
int index = line.IndexOf('#');
if (index != -1) builder.AppendLine(line.Substring(0, index));
}
txtDisplay.Text = builder.ToString();
Don't forget to switch the TextBox to multi-line mode if needed.

Reading data from a text file into a struct with different data types c#

I have a text file that stores data about cars, its call car.txt. I want to read this text file and categorize each of the sections for each car. Ultimately I want to add this information into a doubly linked list. So far everything I have tried is either giving me format exception or out of range exception.
This is my public structure
public struct cars
{
public int id;
public string Make;
public string Model;
public double Year;
public double Mileage;
public double Price;
}
This is where I try reading the data into the struct then add it to the DLL
static void Main()
{
int Key;
cars item = new cars();
int preKey;
/* create an empty double linked list */
DoubleLinkedList DLL = new DoubleLinkedList();
string line;
StreamReader file = new StreamReader(#"C:\Users\Esther\Desktop\cars.txt");
while ((line = file.ReadLine()) != null)
{
Console.WriteLine(line);
var array = line.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
item.Make =array[0];
item.Model = array[1];
item.Year = Double.Parse(array[2]);
item.Mileage = Double.Parse(array[2]);
item.Price = Double.Parse(array[2]);
// Using newline to seprate each line of the file.
Console.WriteLine(line);
DLL.AppendToHead(item);
}
This is throws a format exception then an out of range exception. How do I get this code to read the text file into the struct and add it to my DLL? This is the car.txt file
BMW
228i
2008
122510
7800
Honda
Accord
2011
93200
9850
Toyota
Camry
2010
85300
9500
I've changed your double-linked list to a plain List<cars> for simplicity. You need to create a new cars item for each record, otherwise you'll end up with every element in your list referring to the same record (the last one processed). Each line has a different attribute of the car so you need to work out which attribute to save, using a counter (idx).
using System.Collections.Generic; // for List<cars>
... ... ...
public static void ReadMultiline()
{
// http://stackoverflow.com/questions/39945520/reading-data-from-a-text-file-into-a-struct-with-different-data-types-c-sharp
var DLL = new List<cars>();
string line;
StreamReader file = new StreamReader(#"cars.txt");
var item = new cars();
int idx = 0;
while ((line = file.ReadLine()) != null)
{
idx++;
switch ( idx ) {
case 1: item.Make = line; break;
case 2: item.Model = line; break;
case 3: item.Year = Double.Parse(line); break;
case 4: item.Mileage = Double.Parse(line); break;
case 5: item.Price = Double.Parse(line); break;
}
if (line == "" && idx > 0 )
{
DLL.Add(item);
idx = 0;
item = new cars(); // create new cars item
}
}
// pick up the last one if not saved
if (idx > 0 )
DLL.Add(item);
foreach( var x in DLL )
{
Console.WriteLine( String.Format( "Make={0} Model={1} Year={2} Mileage={3} Price={4}", x.Make, x.Model, x.Year, x.Mileage, x.Price) );
}
}
You are reading the file line by line with ReadLine, and trying to split a single line with a line ending. This will result in an array with just one element (E.G. "BMW")
You can either read the whole file and then split by lines or just assume that each line will contain some data.
The OutOfRangeException refers to your invocation of array[1] when the array contains only array[0] = "BMW".

How do I extract everything inside the double-quotes from a list?

I have the code:
class Program {
static void Main(string[] args) {
const string f = "../../../input.txt";
List < string > lines = new List < string > ();
using(StreamReader r = new StreamReader(f)) {
string line;
while ((line = r.ReadLine()) != null) {
if (line.StartsWith(" <job_number") && line.EndsWith(">")) {
lines.Add(line);
}
}
}
foreach(string s in lines) {
Console.WriteLine(s);
}
Console.Read();
}
}
after the while loop, I run a condition to find any lines that start with some string and end with some string. This is how the string looks like:
<job_number "1234" />
<job_number "1829" />
How do I extract the numbers from inside the quote? At the moment the console prints out the whole line:
<job_number "1234" />
<job_number "1829" />
I want:
1234
1829
I've looked into Regex but it confuses me greatly.
Edit: I need to add that the file I am parsing is a systems configuration file which contains a lot of other data. I have managed to create a list called lines that gets the exact values that I need. I now need to throw some formatting in this list to get the values from the list (everything inside the quotes).
If you are keen on LINQ:
var str = #"<job_number ""1234"" />";
var num = new string(str.Where(c => Char.IsDigit(c)).ToArray());
Console.WriteLine(num); // 1234
In your case, a simple regex match with \d+ will do the job.
//...
while ((line = r.ReadLine()) != null)
{
var re = Regex.Match(line, #"(\d+)");
if (re.Success)
{
var val = re.Groups[1].Value;
lines.Add(val);
}
}
//...
EDIT:
You can of course change the regex for your exact needs, for example:
var re = Regex.match(line, "job_number\\s\"(\\d+)\"");
might be more appropriate if your file contains other numbers as well.
The file you are parsing is practically XML Why not just go all the way and standardize the format to be xml complaint?
<Jobs>
<Job Number="1234" />
<Job Number="1235" />
</Jobs>
Then you could simply use Linq to XML to grab all the Job elements and enumerate their Number attribute.
XDocument doc = XDocument.Load("XMLFile1.xml");
var numbers = from t in doc.Descendants("Job")
select t.Attribute("Number").Value;
foreach (var number in numbers)
{
Console.WriteLine(number);
}
If format of your string is invariable you can do it in one line with a simple Split method :
string value = input.Split('"')[1];
For example :
string[] s =
{
#"<job_number ""1234"" />",
#"<job_number ""1829"" />"
};
for (int i = 0; i < s.Length; i++) Console.Write(s[i].Split('"')[1] +", ");
Output : 1234, 1829
Using IndexOf and Substring will get the job done in a manner of speed and memory and simplicity(part).
if (line.StartsWith(" <job_number") && line.EndsWith(">")) {
int start = line.IndexOf("\"") + 1;
int end = line.IndexOf("\"", start);
if (start > 0 && end > 0)
{
string numberAsString = line.Substring(start, end - start);
int number;
if (int.TryParse(numberAsString, out number))
{
lines.Add(number);
//Console.WriteLine(number);
}
}
}

Categories