【问题标题】:How do I take a certain word from user input and make it a string?如何从用户输入中获取某个单词并使其成为字符串?
【发布时间】:2016-04-27 21:09:47
【问题描述】:

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

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

  • 马克西姆斯

【问题讨论】:

  • 字符串类有一个名为 Split 的方法,它可以破坏整个字符串的各个部分,从而创建一个单词数组。看examples of string.Split
  • 不要从用户那里拿东西! -- 太不礼貌了!

标签: c# console readline


【解决方案1】:
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.");
}

【讨论】:

  • 请注意,您还希望在 '.' 上进行拆分。也许还有其他标点符号,这样最后一个词就不是“球”了。您提出的建议并不像您想象的那么简单。
  • 是的,我知道,你可以走得更远,但可能他开始学习了,所以我尽量保持简单。
【解决方案2】:

做一些类似的事情

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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多