Search code examples
c#stringvisual-studiocharacterpin-code

I have to find a 4 digit PIN code hidden in 3 line text


using System;

namespace HiddenMessageC

{

    class Program

    {
        static void Main(string[] args)
        {
            string encodedPinNumber = Console.ReadLine();
            string startPostionString = Console.ReadLine();
            int step = Convert.ToInt32(Console.ReadLine());

            string pin = "";
            int startPostion = startPostionString[0] - 'a';
            pin += encodedPinNumber[startPostion] + encodedPinNumber[startPostion + step];
            pin += encodedPinNumber[startPostion + 2 * step] + encodedPinNumber[startPostion + 3 * step];

            Console.WriteLine(pin);
            Console.Read();
        }
    }
}

On the first line is a text which length is greater than 4, composed only of digits from 0 to 9.

The second line encodes the index where the hidden Pin code in the text begins. Possible values ​​are the letters a, b or c, and a indicates that the start index is 0, b that the start index is 1, and c that the start index is 2.

On the third line is a number that indicates how many characters we need to skip in the text from the fisrt line (starting with the starting index specified above) to discover the 4 digits of the PIN code.

If I input 123456789, a , 2 => I should get the 1357 result...But my result is => 100108.

Could you give me some suggestions please? :)


Solution

  • As Turo said, when you use the index to access a string, it will return char. When the two char fields perform + operation, they will be automatically converted to int.

    So try to use String.Substring Method to get an individual character.

    pin += encodedPinNumber.Substring(startPostion, 1) + encodedPinNumber.Substring(startPostion + step, 1);
    pin += encodedPinNumber.Substring(startPostion + 2 * step, 1) + encodedPinNumber.Substring(startPostion + 3 * step, 1);
    

    Or store all characters in a list, and then use the index to access them.

    List<string> stringlist = encodedPinNumber.Select(c => c.ToString()).ToList();
    
    pin += stringlist[startPostion] + stringlist[startPostion + step];
    pin += stringlist[startPostion + 2 * step] + stringlist[startPostion + 3 * step];