Home > Net >  C#: How to read one line containing name and two numbers divided by space
C#: How to read one line containing name and two numbers divided by space

Time:10-26

I'd want it to work like in a code below, but instead of enering string, than first integer and than the second one I'd want to input string integer integer in a row divided by space.

 string name = Console.ReadLine();
        int numb1 = Convert.ToInt32(Console.ReadLine());
        int numb2 = Convert.ToInt32(Console.ReadLine());

        Console.WriteLine("Hi {0}, your number is {1}", name, numb1   numb2);

CodePudding user response:

Use the String.Split function. It will return an array of strings, which you can then parse into integers.

CodePudding user response:

Use Split function on loaded string. The parameter in the Split function is the character on which the string will be split. This can occur multiple times if the character appears multiple times in the string. The result is an array of strings.

string input = Console.ReadLine(); //"John 65 10"
string[] splitted = input.Split(" ");

string name = splitted[0];
int numb1 = Convert.ToInt32(splitted[1]);
int numb2 = Convert.ToInt32(splitted[2]);
Console.WriteLine("Hi {0}, your number is {1}", name, numb1   numb2);
  • Related