如何从用户输入中获取某个单词并将其变成字符串?

How do I take a certain word from user input and make it a string?

我想知道如何从输入控制台的句子中提取特定单词并将其定义为字符串。如果有人能解释我是如何做到这一点的,我将非常感激。

用户输入=这是一个红球。 弦球颜色 = 红色 我想从这句话中取出第三个词并将其制成一个字符串,但不知道如何做。到目前为止,我只知道如何使字符串等于控制台读取行。

string userInput = Console.ReadLine();
string color = userInput.Split(' ')[2];

当然,在实际程序中,您应该在尝试从 Split() 方法返回的数组中获取字符串之前检查字符串是否包含 3 个单词,如下所示:

string userInput = Console.ReadLine();
string[] words = userInput.Split(' ');
if (words.Length >= 3) {
    string color = words[2];
    Console.WriteLine("The third word is: " + color);
}
else {
    Console.WriteLine("Not enough words.");
}

做类似的事情

string userInput = Console.ReadLine();
//this will break the user input into an array
var inputBits = userInput.Split(' ');
//you can now directly access the index of the word you seek
var color = inputBits[2];
//You can also iterate over it and do something else...
for(int i = 0; i < inputBits.Length; i++)
{
    var inputBit = inputBits[i];
    //do something else
}