Please help me with the task: Output character number

Hello, I’m working on this task:

Write a program that reads a string and an integer number N from the console. It should then output the string’s _N_th character to the console. For example:
>Make deals with machines
>4
e

Here is my code:


namespace CharType
{
   class OutputCharacterNumber
   {
       static void Main(string[] args)
       {
           string sentens = Console.ReadLine();
           char sent = char.Parse(sentens);

           int number = int.Parse(Console.ReadLine());
           
           char need = sent[number - 1];
           Console.WriteLine(need);
       }
   }
}

Can anyone please help me to solve it?

OR

   {
       string sentens = Console.ReadLine();
       char sent = char.Parse(sentens);

       int number = int.Parse(Console.ReadLine());
       number = number - 1;
       
       char need = sent[number];
       Console.WriteLine(need);
   }

in C# you can get array of chars for free from any string. You don’t need to create one.

string sentens = Console.ReadLine();
int number = int.Parse(Console.ReadLine());
char need = sentens[number];

might work. But one more mistake here is that computer starts counting from 0, so to use “human” nth element you should add -1 to the number variable.

sentens[number-1]; would work much better :slight_smile:

1 Like