我正在开发一款Windows手机应用。在我的应用程序中,我想在文本框中获取最新输入的单词而不是最后一个单词。我想在按下的空格键上更改最新输入的单词。我正在接受像这样的关键事件的最后一句话:
private async void mytxt_KeyUp_1(object sender, KeyRoutedEventArgs e)
{
if (e.Key == Windows.System.VirtualKey.Space || e.Key == Windows.System.VirtualKey.Enter)
{
if (string.IsNullOrWhiteSpace(textBox_string) == false)
{
string[] last_words = Regex.Split(textBox_string, @"\s+");
int i = last_words.Count();
last_words = last_words.Where(x => x != last_words[i-1]).ToArray(); last_word = last_words[last_words.Count() - 1];
last_word = last_word.TrimStart();
}
}
}
我通过这种方法得到了最后一个字,但实际上我想得到用户最新输入的字。意思是,如果用户将光标直接移动到文本框的中间并键入任何单词,那么我想在空格键按下事件上获取该单词;我想要该单词的位置,并可以编程方式更改该单词并更新文本框。 例如,如果用户键入
ħ!!我叫vanani
然后用户在'name'之后直接移动光标,类型'是sohan'
ħ!!我的名字是sohan
然后我想在文本框的关键事件中得到'是'和'sohan'的相同和位置。我需要用另一个单词替换该单词的位置,并用新替换的文本更新文本框。
我见过这些问题。 winforms - get last word..和C# how to get latest char..,但他们没有帮助我。请帮帮我。
答案 0 :(得分:0)
像这样:
if (Regex.IsMatch(textBox_string, @"\S*(?=\s?$)"))
{
Match match = Regex.Match(textBox_string, @"\S*(?=\s?$)");
string word = match.Value;
int startingIndex = match.Index;
int length = word.Length;
}
答案 1 :(得分:0)
我找到了我的问题的答案。 这是为我工作的代码。
Bool isFirst = false;
int mytempindex;
private async void mytxt_KeyUp_1(object sender, KeyRoutedEventArgs e)
{
if (e.Key == Windows.System.VirtualKey.Space)
{
int i = mytxt.SelectionStart;
if (i < mytxt.Text.Length)
{
if (isfirst == false)
{
mytempindex = mytxt.SelectionStart;
isfirst = true;
}
else
{
int mycurrent_index = mytxt.SelectionStart;
int templength_index = mycurrent_index - mytempindex;
string word = mytxt.Text.Substring(mytempindex, templength_index); //It is the latest entered word.
//work with your last word.
}
}
}
}
我认为它并不适用于所有情况,但通过这种方式,您可以了解如何从Textbox或RichTextbox获取最新输入的单词。