Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# WHy does Array.IndexOf return -1

I have started trying to learn c#.

I don’t understand why my use of Array.IndexOf(); returns -1.
I want it to return the index numbers in the alphabet based on the letters in a player_name that you get from user input. I am trying to loop through the characters of the
player_name and capture the index number of that character in the alphabet.

Take a look:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

using System;

namespace FantasyGame
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string player_name = null;

            string[] alphabet = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "æ", "ø", "å", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "æ", "ø", "å" };

            Console.Write("\nEnter your name: ");
            player_name = Console.ReadLine();


            string[] password = { };
            foreach (char c in player_name)
            {
                int index = Array.IndexOf(alphabet, c);
                Console.WriteLine(Array.IndexOf(alphabet, c));
                Console.WriteLine(c);

            }
        }
    }
}

If I replace the c variable with a specific string value such as "k" it returns the correct index number. Why? The ´´´c´´´ has a string value, right?

>Solution :

The c has a string value, right?

No, it has a char value. You can see that where you’ve declared the variable:

foreach (char c in player_name)

There are numerous fixes for this. I’d suggest the simplest is to just make alphabet a string and use string.IndexOf. Alternatively, to keep your code as similar as possible, make alphabet a char[], e.g. by using String.ToCharArray:

char[] alphabet = "abcdefghijklmnopqrstuvwxyzæøåabcdefghijklmnopqrstuvwxyzæøå".ToCharArray();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading