如何从文本框中获取单词

本文关键字:获取 单词 文本 | 更新日期: 2023-09-27 18:35:29

在我的WPF应用程序中,我有一个名为:textBox的文本框。我正在尝试从用户在字符串数组中键入的句子中获取每个单词,例如 arrayWords。我在stackOverFlow上找到了一段代码,它计算单词的数量,但我想复制每个单独的单词。

波纹管是计算字数的代码。

String text = textBox.Text.Trim();
int wordCount = 0, index = 0;
while (index < text.Length)
{
     // check if current char is part of a word
     while (index < text.Length && Char.IsWhiteSpace(text[index]) == false)
        index++;
     wordCount++;
    // skip whitespace until next word
    while (index < text.Length && Char.IsWhiteSpace(text[index]) == true)
        index++;
}

如何从文本框中获取单词

您可以使用 String.Split 函数。

String text = textBox.Text.Trim()
var words = text.Split(' ');

 var words = text.Split(); // Default parameter is taken as whitespace delimiter
虽然

@dotNET答案是正确的,但它假设你应该自己维护标点符号列表(在他的答案中没有完整的)。此外,可能有带连字符的单词。

我建议使用正则表达式:

var words = Regex.Matches(textBox.Text, @"'w+-?'w+")
    .OfType<Match>()
    .Select(m => m.Value)
    .ToArray();

String.Split()可以将您的句子切成单词。但是,您应该注意修剪单词中的标点符号。例如,如果您在句子"StackOverflow 很好,我喜欢它"上使用Split(),则数组中得到的两个单词将附加逗号和句点字符。所以你应该使用这样的东西来获得"纯"的词:

string[] words = textBox.Text.Split().Select(x => x.TrimEnd(",.;:-".ToCharArray())).ToArray();

上面的语句中已经使用了 LINQ,所以你应该导入System.Linq .

以下代码将给出文本框中的单词数组。

string[] words = textBox.Text.Split(" ");
 string[] words = textBox.Text.Split(new char(" "));

从句子中获取单词背后的逻辑是,首先您将句子拆分为单词,然后将这些单词存储到字符串数组中,然后您可以做任何您想做的事情。 下面的代码肯定会帮助您解决问题。

 static void Main(string[] args)
    {
        string sentence = "Thats the sentence";
        string[] operands = Regex.Split(sentence,@" ");
        foreach(string i in operands)
        {
            Console.WriteLine(i);
        }
        Console.ReadLine();
    }

它将从句子中提取单词,并将存储在数组中并显示它们。