1

私のC#プログラム(この時点で)では、フォームに2つのフィールドがあります。1つは、リストボックスを使用した単語リストです。もう1つはテキストボックスです。大きな単語リストをテキストファイルからリストボックスに正常にロードすることができました。次の方法で、リストボックスで選択したアイテムをテキストボックスに表示することもできます。

private void wordList_SelectedIndexChanged(object sender, EventArgs e)
     {
          string word = wordList.Text;
          concordanceDisplay.Text = word;
     }

テキストボックスにコンテンツの一部を表示するために取得する必要のある別のローカルファイルがあります。このファイルでは、(辞書のように)各見出し語の前に#が付いています。したがって、変数'word'を取得し、このローカルファイルを検索して、次のようにエントリをテキストボックスに配置します。

#headword1
    entry is here...
    ...
    ...
#headword2
    entry is here...
    ...
    ...
#headword3
    entry is here...
    ...
    ...

テキストファイルの形式を取得します。その単語の前に#が付いた正しい見出し語を検索し、そこからファイル内の次のハッシュまですべての情報をコピーして、テキストボックスに配置する必要があります。

明らかに、私は初心者なので、優しくしてください。どうもありがとう。

PS私はStreamReaderを使用して単語リストを取得し、次のようにリストボックスに表示しました。

StreamReader sr = new StreamReader("C:\\...\\list-final.txt");
       string line;
       while ((line = sr.ReadLine()) != null)
       {
           MyList.Add(line);
       }
       wordList.DataSource = MyList;
4

2 に答える 2

3
var sectionLines = File.ReadAllLines(fileName) // shortcut to read all lines from file
    .SkipWhile(l => l != "#headword2") // skip everything before the heading you want
    .Skip(1) // skip the heading itself
    .TakeWhile(l => !l.StartsWith("#")) // grab stuff until the next heading or the end
    .ToList(); // optional convert to list
于 2012-05-28T03:24:19.570 に答える
2
string getSection(string sectionName)
{
    StreamReader sr = new StreamReader(@"C:\Path\To\file.txt");
    string line;
    var MyList = new List<string>();
    bool inCorrectSection = false;
    while ((line = sr.ReadLine()) != null)
    {
        if (line.StartsWith("#"))
        {
            if (inCorrectSection)
                break;
            else
                inCorrectSection = Regex.IsMatch(line, @"^#" + sectionName + @"($| -)");
        }
        else if (inCorrectSection)
            MyList.Add(line);
    }
    return string.Join(Environment.NewLine, MyList);
}

// in another method
textBox.Text = getSection("headword1");

以下に、セクションが一致するかどうかを確認する別の方法をいくつか示します。正しいセクション名を検出する際の精度が高い順に並べてあります。

// if the separator after the section name is always " -", this is the best way I've thought of, since it will work regardless of what's in the sectionName
inCorrectSection = Regex.IsMatch(line, @"^#" + sectionName + @"($| -)");
// as long as the section name can't contain # or spaces, this will work
inCorrectSection = line.Split('#', ' ')[1] == sectionName;
// as long as only alphanumeric characters can ever make up the section name, this is good
inCorrectSection = Regex.IsMatch(line, @"^#" + sectionName + @"\b");
// the problem with this is that if you are searching for "head", it will find "headOther" and think it's a match
inCorrectSection = line.StartsWith("#" + sectionName);
于 2012-05-28T03:14:43.403 に答える