gpt4 book ai didi

C# 为什么 Array.IndexOf 返回 -1

转载 作者:行者123 更新时间:2023-12-05 08:14:46 24 4
gpt4 key购买 nike

我已经开始尝试学习 c#。

我不明白为什么我使用 Array.IndexOf(); 会返回 -1。我希望它根据您从用户输入中获得的 player_name 中的字母返回 alphabet 中的索引号。我正在尝试遍历player_name 并捕获该字符在字母表中的索引号。

看看:

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);

}
}
}
}

如果我将 c 变量替换为特定的字符串值,例如 "k",它会返回正确的索引号。为什么? ´´´c´´´ 有一个字符串值,对吧?

最佳答案

The c has a string value, right?

不,它有一个 char 值。您可以在声明变量的位置看到:

foreach (char c in player_name)

有许多针对此问题的修复程序。我建议最简单的方法是将 alphabet 设为字符串并使用 string.IndexOf。或者,为了让您的代码尽可能相似,将 alphabet 设为 char[],例如通过使用 String.ToCharArray:

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

关于C# 为什么 Array.IndexOf 返回 -1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71232767/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com