如何使用c#获取输入的最后一个单词(两个空格字符之间的单词,或者应该考虑新的行,段落或制表符)以及它在Winform RichTextBox中的起始位置和结束位置。我按空格键后需要输入最后一个字
我的代码(工作不正常):
private Word GetLastEnteredWord()
{
string _word = " ";
int pos = rtfText.SelectionStart;
Word word=new Word(_word,pos,0);
if (pos > 1)
{
string tmp = "";
var f = new char();
while (f != ' ' && f != 10 && pos > 0)
{
pos--;
tmp = rtfText.Text.Substring(pos, 1);
f = tmp[0];
_word += f;
}
char[] ca = _word.ToCharArray();
Array.Reverse(ca);
_word = new String(ca);
word.RWord = _word;
word.Si = pos;
word.Length = _word.Length;
}
return word;
}
public class Word
{
public Word(string word, int starti, int len)
{
RWord = word; //word
Si = starti; //start index
Length = len;
}
public string RWord { get; set; }
public int Si { get; set; }
public int Length { get; set; }
}
答案 0 :(得分:3)
使用Substring()
方法做一个小问题:
//KeyPress event handler for your richTextBox
private void richTextBox_KeyPress(object sender, KeyPressEventArgs e){
if(e.KeyChar == ' '){
int i = richTextBox.Text.TrimEnd().LastIndexOf(' ');
if(i != -1) MessageBox.Show(richTextBox.Text.Substring(i+1).TrimEnd());
}
}
答案 1 :(得分:1)
这应该足够了
string lastWord = richTextBox1.Text.TrimEnd().Substring(richTextBox1.Text.TrimEnd()
.LastIndexOf(' ')).Trim();