gpt4 book ai didi

c# - 如何从一个输入行读取以空格分隔的多个输入?

转载 作者:行者123 更新时间:2023-11-30 13:22:56 24 4
gpt4 key购买 nike

假设我有一个要求全名的程序:

string firstName;
string surName;

Console.Write("Enter your full name:");

假设用户输入字符串“Santa Clause”

如果我使用:

firstName = Console.ReadLine();

“圣诞老人”将存储到 firstName,但我只想要“圣诞老人”部分。

当两个或多个单词被空格分隔时,有没有办法只读取第一个单词?还有一种方法可以读出其他词(例如“Clause”)吗?

最佳答案

Is there a way to read only the first word when two or more words are separated by a space?

您可以使用 String.Split()方法。

Returns a string array that contains the substrings in this instance that are delimited by elements of a specified Unicode character array.

喜欢;

string firstName = "Santa Clause";
string[] splitedNames = firstName.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
Console.WriteLine(splitedNames[0]);

输出将是;

Santa

这是一个DEMO .

Is there also a way to read the other words (like "Clause")?

当然,因为 String.Split 返回一个字符串数组,你可以使用数组的索引号找到其他单词,如 splitedNames[1], splitedNames [2]等..

关于c# - 如何从一个输入行读取以空格分隔的多个输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16708520/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com