Home > other >  c# remove space from user input
c# remove space from user input

Time:10-13

I have this task: Task Given an array of ints, print 'true' if the number of '1's is fewer than the number of '4's.

Input Format The first line contains a single integer, n, denoting the size of the array. The second line contains the integers of the array in corresponding order. The mentioned integers are separated by space characters (' ').

Output Format Simply the word 'True' or 'False'.

Sample Input

2
1 4

Output Format False

And this is my code:

int szam = Convert.ToInt32(Console.ReadLine());
int[] szamok = new int[szam];
int szam1 = 0;
int szam4 = 0;


for (int i = 0; i < szamok.Length; i  )
{
    int ertek = Convert.ToInt32(Console.ReadLine());    
    
    szamok[i] = ertek;
}
foreach (int i in szamok)
{
    if (i == 1)
    {
        szam1  ;
    }
    if (i == 4)
    {
        szam4  ;
    }
}
if (szam4 > szam1 && szam4 != szam1)
{
    Console.WriteLine("True");
}
else
{
    Console.WriteLine("False");
}

This code is work for me right when, i use it in visual studio, but it do not work in the website where i need to put my code because the user input coming with spaces.

explain how the input coming in the website: 1 4 3 1 so when i run it got the "Input string was not in a correct format" error, because of the spaces. How can i read the numbers from the input without spaces? Thx for help.

CodePudding user response:

You can use string.Split:

string[] input = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries);
int[] numbers = Array.ConvertAll(input, int.Parse);

Of course it would be better to use int.TryParse because the user can enter invalid integers:

int[] numbers = input
    .Select(s => int.TryParse(s, out int i) ? i : new Nullable<int>())
    .Where(i => i.HasValue)
    .Select(i => i.Value)
    .ToArray();
  • Related