Let's say I have a program that asks for the Full Name:
string firstName;
string surName;
Console.Write("Enter your full name:");
let's say the user inputs the string "Santa Clause"
if I use:
firstName = Console.ReadLine();
"Santa Clause" will be stored to firstName, but I only want the "Santa" part.
Is there a way to read only the first word when two or more words are separated by a space? Is there also a way to read the other words (like "Clause")?
Is there a way to read only the first word when two or more words are separated by a space?
You can use String.Split()
method.
Returns a string array that contains the substrings in this instance that are delimited by elements of a specified Unicode character array.
Like;
string firstName = "Santa Clause";
string[] splitedNames = firstName.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
Console.WriteLine(splitedNames[0]);
Output will be;
Santa
Here is a DEMO
.
Is there also a way to read the other words (like "Clause")?
Sure, since String.Split
return a string array, you can find the other words using the index number of array like splitedNames[1]
, splitedNames[2]
, etc..
try Console.ReadLine().Split(' ')
which will give you string[]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With