StreamReader和2d数组 [英] StreamReader and a 2d array

查看:92
本文介绍了StreamReader和2d数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好



我有这样的文字文件



nam,nam

sa,ds

qw,df

gf,dfg

rt,jk

fg, lo b / b


我想在这个文本文件中找到df。



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.

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

           }





i知道我需要使用a和sr和2,1但我真的不知道我该怎么做。



PLZ任何人都可以帮我吗



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

推荐答案

首先,我不需要使用StreamReader - 我更有可能改为使用File.ReadAllLines:它读取一个字符串数组,每个字符串只有一行。

我要做的第二件事是不使用固定大小的数组(如果只是因为那里)目前你的文本文件中有六个元素...) - 相反,我会使用一个可以容纳两个元素的List,因为看起来你想要存储数据。有一个类可以做得很好:KeyValuePair。

所以:

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:
string[] lines = File.ReadAllLines("FnNam.txt");
List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>();
foreach (string line in lines)
    {
    ...
    }

接下来要做的是查看每行文本并将其分解为部分之前和部分在逗号之后。幸运的是,.NET有一个帮助方法:string.Split。使用它根据逗号将行拆分为两半:

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:

string[] parts = line.Split(',');

然后您可以将这两个部分保存在列表中以供日后使用:

Then you can save the two parts in your list for later:

if (parts.Length == 2)
    {
    list.Add(new KeyValuePair<string,string>(parts[0], parts[1]);
    }



另外你可以看到它df部分同时存在。


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


这篇关于StreamReader和2d数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆