在句子之间提取与最后一个单词不同的单词

问题描述 投票:-1回答:1

我想从文本框中捕获输入并提取与最后一个单词不同的单词,并想知道如何在c#中完成它

private void button1_Click(object sender, EventArgs e)
{
    string s = inputTextBox.Text;
    string[] parts = s.Split(' ');
    string lastword = parts[parts.Length - 1];

    if (s != lastword)
    {                        
    }
}
c# winforms
1个回答
0
投票

这是一个System.Linq解决方案。这将返回所有不是最后一个单词的单词。

string s = "hello this is my list hello";
string[] parts = s.Split(' ');

var words = parts.Where(w => w != parts.Last());

// write to console
Console.WriteLine(string.Join(",", words));

// output
// this,is,my,list

另一种选择是使用循环:

string s = inputTextBox.Text;
string[] parts = s.Split(' ');
string lastword = parts[parts.Length - 1];

for (int i = 0; i < parts.Length - 1; i++)
{
    if (parts[i] != lastword)
    {
        // do something                  
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.