私はテキストファイルを読み、お互いから単語を切り取りたいです、例えばこれは私のテキストファイルです:
asdasdcasf
ガス
asdf
_
_
今、私は「asd」、次に「asdc」、次に「asf」を読みたいです...どうすればそれを行うことができますか?
私はテキストファイルを読み、お互いから単語を切り取りたいです、例えばこれは私のテキストファイルです:
asdasdcasf
ガス
asdf
_
_
今、私は「asd」、次に「asdc」、次に「asf」を読みたいです...どうすればそれを行うことができますか?
List<string> words = new List<string>();
string line;
char[] sep = new char[] { ' ', '\t' };
try
{
System.IO.StreamReader file = new System.IO.StreamReader("c:\\test.txt");
while ((line = file.ReadLine()) != null)
{
words.AddRange(line.Split(sep, StringSplitOptions.RemoveEmptyEntries));
}
file.Close();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
このコードは、テキスト ファイルを 1 行ずつ読み取り、各行を (スペースとタブで) 単語に区切ります。例外は自分で処理する必要があります。
StreamReader の ReadLine を使用すると、次のように行ごとに読み取ることができます。
システムを使用する; System.IO の使用;
クラス テスト {
public static void Main()
{
try
{
// Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
String line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
catch (Exception e)
{
// Let the user know what went wrong.
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
}
}