Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

282
Visualizações
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:

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?

over 4 years ago · Santiago Trujillo
5 Respostas
Responde à pergunta

0

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();
over 4 years ago · Santiago Trujillo Relatório

0

Your c is not a string value, is a char

over 4 years ago · Santiago Trujillo Relatório

0

Replace

int index = Array.IndexOf(alphabet, c);

with

int index = Array.IndexOf(alphabet, c.ToString());

see the official docs,

alphabet is an array of string, so we should pass a string to the second parameter of Array.IndexOf

over 4 years ago · Santiago Trujillo Relatório

0

This happens because you are comparing "c" which is of type Char with an alphabet letter which is of type String. What you can do is just change the type of the array you are using to Char[] like this.

char[] 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', 'æ', 'ø', 'å' }; 

Also pay attention to the quotes in which char types use single quotes ' ' but string types use double quotes " " .

over 4 years ago · Santiago Trujillo Relatório

0

MSDN Documentation of Array.IndexOf() says

Searches for the specified object and returns the index of its first occurrence in a one-dimensional array or in a range of elements in the array.


Now in your code,

  • If you look at closely, your alphabet array is an array of string

  • your code int index = Array.IndexOf(alphabet, c) is trying to find unicode char value in alphabet string and that is why you are getting -1 as a result.

  • To make it work, type of alphabet and type of c needs to be same. Same in the sense, if alphabet is a char[] then c should be char.

  • You can achieve it in two ways,

    1. Converting alphabet as an array of char
    2. Converting c to string.

First Approach,

char[] alphabet = "abcdefghijklmnopqrstuvwxyzæøåabcdefghijklmnopqrstuvwxyzæøå".ToCharArray();
int index = Array.IndexOf(alphabet, c);  //here alphabet is a type of char array

Second Approach,

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", "æ", "ø", "å" };

int index = Array.IndexOf(alphabet, c.ToString());
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda