Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Read Multiple Inputs separated by a space from one input line?

Tags:

c#

input

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")?

like image 283
DarkPotatoKing Avatar asked Dec 09 '22 15:12

DarkPotatoKing


2 Answers

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..

like image 135
Soner Gönül Avatar answered Dec 11 '22 07:12

Soner Gönül


try Console.ReadLine().Split(' ') which will give you string[]

like image 38
dkozl Avatar answered Dec 11 '22 07:12

dkozl