我提示用户在一个提示中输入他们的第一个中间名和姓氏。因此,如果他们键入例如 John Ronald Doe,我如何从该字符串中获取这些值并将它们分配给 fname、mname、lname,以创建一个采用这些值的人员构造函数。
基本上我的问题是如何在一个提示中为用户获取多个值,然后将它们分配给构造函数的不同变量。
谢谢!
Just grab the line then split on white spaces. You'll have to do some input validation to make sure they actually enter fName mName lName
but I'll leave that to you because what you do is dependent on how robust the application needs to be. By that I mean, what happens if the user only enters two words? Do you just assume it's first and last name and set their middle name to String.Empty
? What happens if they enter 4 or 5 words?
string[] tokens = Console.ReadLine().Split(' ');
if (tokens.Length == 3)
{
// do assignment
}
With regard to your comment;
That is more or less correct. Really what's happening is ReadLine()
is returning a string. I'm just calling Split(' ')
directly on that result. You could break it into two lines if you'd like but there's no reason to. Split(char delimiter)
is an instance method in the String
class. It takes a char and returns an array of strings. I'm using tokens because it's kind of a common term. The line is build of three tokens, the first, middle, and last names. It's important to understand that I am not adding anything to an array, Split(' ')
is returning an array. string[] tokens
is just declaring a reference of type string[]
, I don't have to worry about the size or anything like that.
An example to get an array of ints from the input. Note, if any of the input is not a valid integer this will throw an exception.
int[] myInts = Console.ReadLine.Split(' ').Select(x => int.Parse(x)).ToArray();
In this example I'm using LINQ on the result of the split. Split returns a string array. Select
iterates over that array and applies the lambda expression I pass it to each of it's values. It's best to think of x
as the current value. The Select
call here is roughly equivalent to;
List<int> myInts = new List<int>();
foreach (string s in tokens)
{
myInts.Add(int.Parse(s));
}
int[] myIntArray = myInts.ToArray();
If you can't trust the user input you should use TryParse
. I don't know if you can use that as part of a lambda expression (it wouldn't surprise me if you could but it seems like a pain in the ass so I wouldn't bother) instead I'd do;
List<int> myInts = new List<int>();
int temp;
foreach (string s in tokens)
{
if (int.TryParse(s, temp)
myInts.Add(temp);
else
// the input wasn't an int
}
int[] myIntArray = myInts.ToArray();