0

スペースバーでキープレス イベントをトリガーするリッチ テキスト ボックスがあります。私が実装した最後に書かれた単語のすべての出現回数を見つけるロジックは次のとおりです。

private void textContainer_rtb_KeyPress_1(object sender, KeyPressEventArgs e)
    {
        //String lastWordToFind;
        if (e.KeyChar == ' ')
        {
            int i = textContainer_rtb.Text.TrimEnd().LastIndexOf(' ');
            if (i != -1)
            {
                String lastWordToFind = textContainer_rtb.Text.Substring(i + 1).TrimEnd();

                int count = new Regex(lastWordToFind).Matches(this.textContainer_rtb.Text.Split(' ').ToString()).Count;
                MessageBox.Show("Word: " + lastWordToFind + "has come: " + count + "times");
            }

        }
    }

しかし、うまくいきません。誰かがエラーを指摘したり、修正したりできますか?

4

2 に答える 2

1

正規表現は次のようには機能しません:

int count = new Regex(lastWordToFind).Matches(this.textContainer_rtb.Text.Split(' ').ToString()).Count;

この部分:

this.textContainer_rtb.Text.Split(' ').ToString()

テキストを文字列の配列に分割します:

string s = "sss sss sss aaa sss";
string [] arr = s.Split(' '); 

分割後のarrは次のようになります。

arr[0]=="sss"
arr[1]=="sss"
arr[2]=="sss"
arr[3]=="aaa"
arr[4]=="sss"

次に、ToString()は型名を返します。

System.String[]

だから、あなたが実際にやっていることは次のとおりです。

int count = new Regex("ccc").Matches("System.String[]").Count;

それがうまくいかない理由です。あなたは単に行う必要があります:

 int count = new Regex(lastWordToFind).Matches(this.textContainer_rtb.Text).Count;
于 2013-09-18T14:55:46.533 に答える