6

我正在尝试用通过控制台输入的字符串中的字符填充数组。我已经尝试了下面的代码,但它似乎不起作用。我在 for 循环部分得到了 Index out Of Range 异常,我不明白它为什么会发生。for 循环范围不正确吗?任何见解将不胜感激

            Console.WriteLine("Enter a string: ");
            var name = Console.ReadLine();

            var intoarray = new char[name.Length];
            for (var i = 0; i <= intoarray.Length; i++)
            {
                intoarray[i] = name[i];
            }
            foreach (var n in intoarray)
                Console.WriteLine(intoarray[n]);
4

6 回答 6

9

使用ToCharArray()字符串可以转换为字符数组。

Console.WriteLine("Enter a string: ");
var name = Console.ReadLine();

var intoarray= name.ToCharArray();

foreach (var n in intoarray)
    Console.WriteLine(n);

如果您使用的是 foreach,您应该等待索引的行为就像您正在获取值一样。

Console.WriteLine(n);
于 2018-10-05T03:05:51.000 回答
3

由于数组从 0 开始并且您计算的长度包括在内,因此最后一次迭代将超出界限。只需将循环条件更新为小于长度而不是小于或等于..

于 2018-10-05T03:06:37.690 回答
2

I like snn bm's answer, but to answer you question directly, you're exceeding the length of the input by one. It should be:

        for (var i = 0; i <= intoarray.Length - 1; i++)

(Since strings are zero-indexed, the last character in the underlying array is always going to be in the position of arrayLength - 1.)

于 2018-10-05T03:09:03.553 回答
1
  • 1: the iteration should be for (var i = 0; i < intoarray.Length; i++)

  • 2: the code

    foreach (var n in intoarray) Console.WriteLine(intoarray[n]);

    also throws an exception, for "n" is a character in the array while it's used as array index.

  • 3: In addition there's a much easier way to convert string to char array

    var intoarray = name.ToCharArray();

    Here's the result

于 2018-10-05T04:08:29.517 回答
0

Here is your mistake. There are so many options to represent i < intoarray.Length.

for (var i = 0; i < intoarray.Length; i++) // original was i <= intoarray.Length in your code
{
    intoarray[i] = name[i];
}
于 2018-10-05T03:51:57.680 回答
-1

With linq:

  // Select all chars
  IEnumerable<char> intoarray =  
    from ch in name  
      select ch;  // can use var instead of IEnumerable<char>

    // Execute the query  
    foreach (char temp in intoarray)  
        Console.WriteLine(temp);  
于 2018-10-05T04:17:35.097 回答