PreslavMihaylov
PreslavMihaylov

Reputation: 55

printing certain digits from a string c#

I am trying to solve a problem concerning inputing a string of numbers and checking whether the third digit from the number is "7" or not. Here is what I came up with until now:

            string outnum;
            int num1;
            int[] num;
            num = new int[100];

            while (true)
        {
            Console.WriteLine("Input number:");
            outnum = Console.ReadLine();
            if (int.TryParse(outnum, out num1))
            {
                for (int i = 1; i <= 100; i++) 
                {
                    num[(int)i] = Convert.ToInt32(Convert.ToString(outnum[(int)i]));
                }

                if (num[3] == 7)
                {
                    Console.WriteLine("The third digit is 7");
                    break;
                }
                else
                {
                    Console.WriteLine("The third digit is not 7");
                    break;
                }


            }
        }

However, I get an error in the for loop, because in order for it to work correctly, the string inputed from the console should be with as much characters as the "i" int. Therefore I am asking for help in this case. How can I make a string with a length of 100 without being necessary to input 100 characters?

Upvotes: 1

Views: 233

Answers (4)

HackerMan
HackerMan

Reputation: 914

If you are just concerned about the third character in C# numbers start from 0

string values="fg7gdhjdhd";
string val=values.Substring(2,1);
int number=Convert.ToInt32(val);

Upvotes: 0

Steve
Steve

Reputation: 216293

Just using LinQ

if (int.TryParse(outnum, out num1))
{
    List<int> numbers = outNum.ToCharArray()
                        .Select(x => Convert.ToInt32(x.ToString()))
                        .ToList();
    if(numbers[2] == 7)
        Console.WriteLine("Is 7");
    else
        Console.WriteLine("Not 7");
}

No need to keep a fixed length array (however 100 slots seems to be a bit excessive for an integer number).
Notice that I have changed the index of the List to 2 not 3 because the arrays start always at index zero, so, the third digit is retrieved using the index 2.

Upvotes: 0

Christos
Christos

Reputation: 53958

You could use something like this:

input[2]=="7"

in order to check if the third character of your string (I called it input) is seven.

Upvotes: 1

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236218

Use String.Length property:

  for (int i = 0; i < outnum.Length; i++) 

Or simply instead of loop outnum[2] == '7' (remember - indexing starts from zero).

Upvotes: 3

Related Questions