假设
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/