为什么这段代码会给出“索引超出数组范围”的错误?

时间:2018-03-28 12:34:34

标签: c#

此代码基本上应将用户输入拆分为组件字母,然后输出数组中的第1,第3和第5个字母

bool greater = false;
Console.WriteLine("Enter your name: ");
string userName3 = Console.ReadLine();
while (greater = false)
{
   if (userName3.Length >= 5)
   {
      greater = true;
   }
   else
   {
      Console.WriteLine("The name must be 5 characters or more");
   }
}
string[] userNameArr = userName3.Split();
Console.WriteLine(userNameArr[0] + " " + userNameArr[2] + " " + userNameArr[4]);

当我运行最后一行时会导致错误

  

索引超出了数组的范围

为什么会这样,我该如何解决?

5 个答案:

答案 0 :(得分:3)

Split()不会通过检测并将WhiteSpace字符拆分为字符串数组而拆分为char

如果要获取字符,请按索引char firstChar = userName3[0];

访问输入字符串
Console.WriteLine(userName3[0] + " " + userName3[2] + " " + userName3[4]);

而不是

string[] userNameArr = userName3.Split();
Console.WriteLine(userNameArr[0] + " " + userNameArr[2] + " " + userNameArr[4]);

旁注: 将while (greater = false)替换为while (!greater)while (greater == false),因为您要进行比较而不是分配

答案 1 :(得分:0)

这应该有效:

bool greater = false;
while (greater == false)
{
   Console.WriteLine("Enter your name: ");
   string userName3 = Console.ReadLine();
   if (userName3.Length >= 5)
   {
      greater = true;
   }
   else
   {
      Console.WriteLine("The name must be 5 characters or more");
   }
}
string[] userNameArr = userName3.Split();
Console.WriteLine(userNameArr[0] + " " + userNameArr[2] + " " + userNameArr[4]);

该行:

while (greater = false)

实际上将false赋予更大,这意味着你永远不会离开循环。此外,您需要循环内的ReadLine,以便再次提示用户

答案 2 :(得分:0)

String是char数组,因此要获取特定字符使用索引而不是split()

例如要从字符串中获取5个字母,请使用userNameArr[4]

这是从字符串

中读取字符的正确方法
    using System;

    public class Program
    {
        public static void Main()
        {
            bool greater = false;
            Console.WriteLine("Enter your name: ");
            string userName3 = Console.ReadLine();
            while (greater == false)
                {
                    if (userName3.Length >= 5)
                        {
                            greater = true;
                        }
                    else
                        {
                            Console.WriteLine("The name must be 5 characters or more");
                        }
                }
//Indexing to string is used to get letters from string
                Console.WriteLine(userName3[0] + " " + userName3[2] + " " + userName3[4]);
        }
    }

实施:DotNetFiddler

答案 3 :(得分:0)

默认情况下,

userName3.Split()会在空格上拆分用户名,因此,如果用户名为phuzi,则拆分将生成包含单个项["phuzi"]的数组,则只有userNameArr[0]为有效。任何尝试访问其他任何内容都会导致您看到的错误

答案 4 :(得分:0)

发生这种情况是因为数组不包含此索引。 这条线

7!

你想分成什么? 在问这个问题之前你有没有搜索过? 检查一下 What method in the String class returns only the first N characters?