Click here to Skip to main content
15,881,516 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello

I have a text file like this

nam,nam
sa,ds
qw,df
gf,dfg
rt,jk
fg,lo

and i want to find the df in this text file.

C#
string[,] a = new string[5,1];
           using (StreamReader sr = new StreamReader("FnNam.txt"))
           {

           }


i know i need to use a and sr and 2,1 but i relly dont know how im going to do it.

plz can anyone help me with it
Posted
Comments
[no name] 20-Mar-13 15:34pm    
Homework still?
Use sr to read the file to the end.
Split each line and put the elements into a.
Either find "df" as you go through the file or find "df" as you iterate through the array or write a LINQ query.

1 solution

First off, I wouldn't necessaryliy use a StreamReader - I'd be more likely to use File.ReadAllLines instead: it reads to an array of strings, with a single line per string.
The second thing I'd do is not use a fixed size array (if only because there are six elements in your text file at the moment...)- instead I would use a List which could hold two elements, since it would appear that you want to store the data. There is a class which would do it nicely: KeyValuePair.
So:
C#
string[] lines = File.ReadAllLines("FnNam.txt");
List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>();
foreach (string line in lines)
    {
    ...
    }
The next thing to do is to look at each line of text and break it into the part before and the part after the comma. Fortunately, .NET has a helper method for that: string.Split. Use it to split the line into two halves based on the comma:
C#
string[] parts = line.Split(',');
Then you can save the two parts in your list for later:
C#
if (parts.Length == 2)
    {
    list.Add(new KeyValuePair<string,string>(parts[0], parts[1]);
    }

In addition you can see it the "df" part exists at the same time.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900