c# - 如何在 RichTextBox 中获取点击的单词编号( Index )

标签 c# winforms

假设

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

如果 Caret 位置位于单词中:

  • 信息,我要获取6
  • ,我要得到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.Matches 获取单词分词模式...然后将 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();

最佳答案

我建议这样做:

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”,以增加每个单词的数量。但我认为你还必须过滤掉可能的东西,。 ;等等,只计算单词。但这取决于您使用它的目的。

关于c# - 如何在 RichTextBox 中获取点击的单词编号( Index ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54113554/

相关文章:

c# - 错误的变量得到更新

c# - USPS 费率计算器的回复

c# - 在 Windows Form APP 中打开 WPF 窗口

c# - 键入单个数字时,DateTimePicker 值不会更新 onLeave

c# - C# 中的 MVC 赢了。表格申请

c# - 为什么在使用 Entity Framework 实现存储库模式时使用接口(interface)?

c# - 如何在多个操作系统版本上测试 Windows 应用程序

c# - 清除网络浏览器控件中的选择

c# - 为什么 MSChart 不填充整个图表区域?

c# - 根据文件填充一组复选框