如何在RichTextBox中获得单击的单词数(索引)

时间:2019-01-09 15:38:08

标签: c# winforms

假设

richTextBox1.Text = "Your description gives people the information they need to help you answer your question."

如果插入符号位置位于单词中:

  • information,我想得到6
  • gives,我想得到3
  • ...等等...

编辑:- 感谢所有贡献者...

在答案中有两种逻辑。

1-从开始到单击位置选择文本,然后使用(string.Split)拆分单词并对其计数。

var start = richTextBox1.SelectionStart;
var substring = richTextBox1.Text.Substring(0, start);
var wordscount = substring.Split(" ,.:;\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Length;
 Label1.Text = wordscount.ToString();

2-使用Regex获取单词标记模式。匹配...然后将match.Index与点击位置进行比较

        int i = 1;
        string text = richTextBox1.Text;
        string tokenizingPattern = @"(\[[^][]*]|#[^#]*#)|\s+";

        //Create lookup
        List<Tuple<string, int, int>> tokenizedWordLookup = new List<Tuple<string, int, int>>();

        tokenizedWordLookup.Add(Tuple.Create<string, int, int>("", i++, 1));
        foreach (Match match in Regex.Matches(text, tokenizingPattern, RegexOptions.Singleline))
            tokenizedWordLookup.Add(Tuple.Create<string, int, int>(match.Value, i++, match.Index));

        //Return the word index where the selection start is equal to the tokenizing word start
        Label1.Text = tokenizedWordLookup.LastOrDefault(x => x.Item3 <= richTextBox1.SelectionStart)?.Item2.ToString();

3 个答案:

答案 0 :(得分:3)

我建议这样做:

public Form1()
    {
        InitializeComponent();

        richTextBox1.Click += RichTextBox1_Click;
    }

    private void RichTextBox1_Click(object sender, EventArgs e)
    {
        var start = richTextBox1.SelectionStart;
        var substring = richTextBox1.Text.Substring(0, start);
        var words = substring.Split(new string[] { " ", "\r\n" }, StringSplitOptions.None);
        var count = words.Length;

        labelCurrentWordNumber.Text = count.ToString();
    }

当光标在单词前面时,它将不包含单词。如果可以,请设置StringSplitOptions.None

编辑:我为换行符添加了“ \ r \ n”,以增加每个单词的数量。但是我想你也必须过滤掉事情,。 ;等等,只算单词。但这取决于您使用它的目的。

答案 1 :(得分:1)

不如Malior的解决方案优雅,但这也可以。

private int currentWordIndex()
{
    int currentWordIndex = 1;
    int charactersCounted = 1;

    if (richTextBox1.SelectionStart != 0)
    {
        foreach (Char character in richTextBox1.Text)
        {
            charactersCounted++;

            if (char.IsWhiteSpace(character))
                currentWordIndex++;

            if (charactersCounted == richTextBox1.SelectionStart)
                break;
        }
    }

    else
        currentWordIndex = 1;

    return currentWordIndex;
}

只需复制此方法,然后将currentWordIndex()添加到richTextBox1_Click事件中即可。

答案 2 :(得分:1)

您可以采用这种方法:

  1. 首先构造单词的查询
  2. 找到选择的开始和结束
  3. 获取单词索引

您可以从here获得@WiktorStribiżew提供的单词标记模式。

这是完整的代码:

public Form1()
{
    InitializeComponent();

    richTextBox1.Click += RichTextBox1_Click;
}

private void RichTextBox1_Click(object sender, EventArgs e)
{
    var start = richTextBox1.SelectionStart;


    string text = richTextBox1.Text;
    string tokenizingPattern = @"(\[[^][]*]|#[^#]*#)|\s+";

    // Create lookup
    List<Tuple<string, int, int, int>> tokenizedWordLookup = new List<Tuple<string, int, int, int>>();

    int i = 1;
    foreach (Match match in Regex.Matches(text, tokenizingPattern, RegexOptions.Singleline))
        tokenizedWordLookup.Add(Tuple.Create<string, int, int, int>(match.Value, i++, match.Index, match.Index + match.Length));

    // Find the word index where the selection start is equal to the tokenizing word start
    Tuple<string, int, int, int> foundTuple = (tokenizedWordLookup.Where(x => x.Item3 >= start && x.Item4 <= start).FirstOrDefault()) ?? Tuple<string, int, int, int> foundTuple

    labelCurrentWordNumber.Text = foundTuple.Item2.ToString();
}