Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/312.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在避免索引越界的同时重新分配数组中的值_C#_Arrays - Fatal编程技术网

C# 如何在避免索引越界的同时重新分配数组中的值

C# 如何在避免索引越界的同时重新分配数组中的值,c#,arrays,C#,Arrays,我有一个类似以下内容的列表: "StudentA, Math, Mrs.Jones, Sixth, 98, 92, 90, , 40" "StudentB, Science, Mrs.Williams, Second, , 91, 70, 50, 41" "StudentC, History, Mr.Webber, Eighth, 100, 92, 90, 75, 40" "StudentD, Art, Mrs.Gonzalez, Fourth, 99, 91, 85,, 40" 我想做的是:

我有一个类似以下内容的列表:

"StudentA, Math, Mrs.Jones, Sixth, 98, 92, 90, , 40"
"StudentB, Science, Mrs.Williams, Second, , 91, 70, 50, 41"
"StudentC, History, Mr.Webber, Eighth, 100, 92, 90, 75, 40"
"StudentD, Art, Mrs.Gonzalez, Fourth, 99, 91, 85,, 40"
我想做的是:对于每个空白记录(即没有值的逗号-90,40。第二个逗号是空白记录),我想将其默认为0

在我的尝试中,我不断得到索引越界异常。这是我的尝试:

foreach (string element in studentList)
{
   string[] studentSplit = element.Split(',');
   studentSplit[Array.IndexOf(studentSplit, "")] = "0";
}

代码将在第一次迭代中工作,但在任何后续迭代后崩溃。然而,我不知道为什么这是一个索引越界异常。我没有分配尺码。任何帮助都将不胜感激。

如果找不到,索引将为-1,超出范围

int ind;
while((ind = Array.IndexOf(ssplit, "")) >= 0)
{
    ssplit[ind] = "fix";
}

您遇到的问题是,如果studentSplit数组中没有出现“”,array.IndexOf(studentSplit,“”)返回-1,这超出了studentSplit数组的范围。而“”实际上是一个“”

试试这个:

        foreach (string element in studentList)
        {
            string[] studentSplit = element.Split(',');
            for (int i = 0; i < studentSplit.Length - 1; i++)
            {
                studentSplit[i] = studentSplit[i] == " " ? "0" : studentSplit[i];
            }
        }
foreach(学生列表中的字符串元素)
{
字符串[]studentSplit=element.Split(',');
for(int i=0;i
List s=new List();
s、 加上(“学生,数学,琼斯夫人,第六,98,92,90,40”);
s、 添加(“学生B,科学,威廉姆斯夫人,第二,91,70,50,41”);
s、 添加(“学生C,历史,韦伯先生,第八,100,92,90,75,40”);
s、 添加(“学生,艺术,冈萨雷斯夫人,第四,99,91,85,40”);
foreach(s中的var项目)
{
字符串[]studentSplit=item.Split(',');
studentSplit.Where(x=>x.Trim().Length==0.ToList().ForEach(y=>studentSplit[Array.LastIndexOf(studentSplit,y)]=“0”);
}
这就行了。 现在回答你的问题

我不断得到索引越界异常

因为如果找不到Array.IndexOf,它将为您提供-1。Array[-1]将为您提供OutofBound异常

只是一个建议,对于字符串输入,请始终使用修剪函数。如果您正在处理需要索引的此类场景,请在安全的情况下使用ToUpper case

foreach (string element in studentList)
{
    string[] studentSplit = element.Split(',');
    studentSplit[Array.IndexOf(studentSplit, "")] = "0";
}
这句话的问题是你在寻找一个“你”,而你要找的空白空间大部分是“”。 一种解决方案是迭代studentSplit并检查每个字符串,在Comparison上添加替换(“,”),这样

for(int i = 0; i < studentSplit.Length; i++)
{
     studentSplit[i] = studentSplit[i].Replace(" ","").Equals("") ? "0" : studentSplit[i];
}
for(int i=0;i

这应该满足您的需要,并且它适用于“”和“”。

这段代码实际上有很多错误

foreach (string element in studentList)
{
    string[] studentSplit = element.Split(',');
    studentSplit[Array.IndexOf(studentSplit, "")] = "0";
}
你在每个学生之间循环,这很好。然后通过
Split(…)
创建一个学生值数组,这很好。但是,您正在单个学生值(拆分结果)中查找一个空字符串,这看起来非常奇怪。我认为这是检查学生值是否为空的支票,对吗?如果是这样的话,这是错误的做法,因为你没有考虑到空格。然后使用该索引(学生值中字符的索引)作为学生部分的访问器索引。这对我来说毫无意义,我只能假设你想访问完整学生字符串中该字符的索引,而不是访问部分本身。由于这些域不匹配(学生部分中的索引与学生部分中的索引),因此最终必然会出现
IndexOutOfBoundException

基本上,算法的前提是错误的,因为您没有考虑学生全文中每个学生值的偏移量,并且没有考虑空白

所以这里有一种不同的方法。我不是说这是最好的。我只是说我觉得这更符合你的要求

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
            var students =
                new [] {
                    "StudentA, Math, Mrs.Jones, Sixth, 98, 92, 90, , 40",
                    "StudentB, Science, Mrs.Williams, Second, , 91, 70, 50, 41",
                    "StudentC, History, Mr.Webber, Eighth, 100, 92, 90, 75, 40",
                    "StudentD, Art, Mrs.Gonzalez, Fourth, 99, 91, 85,, 40"
                };

        foreach (var student in WithDefaultStudentValues(students))
        {
            Console.WriteLine(student);
        }
    }

    public static IEnumerable<string> WithDefaultStudentValues(IEnumerable<string> students)
    {
        foreach (var student in students)
        {
            var studentValues =
                student
                    .Split(',')
                    .Select(value => string.IsNullOrWhiteSpace(value) ? "0" : value);

            yield return string.Join(",", studentValues);
        }
    }
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
公共课程
{
公共静态void Main()
{
var学生=
新[]{
“学生塔,数学,琼斯夫人,第六,98,92,90,40”,
“学生B,科学,威廉姆斯夫人,第二,91,70,50,41”,
“学生C,历史,韦伯先生,第八,100,92,90,75,40”,
“学生,艺术,冈萨雷斯夫人,第四,99,91,85,40”
};
foreach(var student in with DefaultStudentValues(students))
{
控制台。WriteLine(学生);
}
}
带有DefaultStudentValue的公共静态IEnumerable(IEnumerable students)
{
foreach(学生中的var学生)
{
var学生价值观=
学生
.Split(“,”)
.Select(value=>string.IsNullOrWhiteSpace(value)?“0”:value);
返回字符串。Join(“,”,studentValues);
}
}
}

你真的应该创建一个
学生
类并使用
列表
。将每个输入字符串解析为类的实例。对字段使用nullable
int
s。这种方法正在折磨一种非常好的面向对象编程语言。有没有办法在我现有的循环中处理这个问题?@Cuphead你不知道如何测试小于0的值?我只是想看看我是否可以在没有嵌套循环的情况下做这件事。请看我的(被否决的)答案。这说明了什么“如何在避免索引越界的同时重新分配数组中的值”?@rory.ap当索引越界时,您不会分配值。这是对“我不确定为什么这是索引越界异常”的直接回答。如果输入与“”类似,则这将不起作用,而“”正是StudentD rowTesting
String.IsNullOrWhiteSpace(studentSplit[i])
将处理多个(或无)空格。使用
if
而不是
将更明显地向re发出信号
using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
            var students =
                new [] {
                    "StudentA, Math, Mrs.Jones, Sixth, 98, 92, 90, , 40",
                    "StudentB, Science, Mrs.Williams, Second, , 91, 70, 50, 41",
                    "StudentC, History, Mr.Webber, Eighth, 100, 92, 90, 75, 40",
                    "StudentD, Art, Mrs.Gonzalez, Fourth, 99, 91, 85,, 40"
                };

        foreach (var student in WithDefaultStudentValues(students))
        {
            Console.WriteLine(student);
        }
    }

    public static IEnumerable<string> WithDefaultStudentValues(IEnumerable<string> students)
    {
        foreach (var student in students)
        {
            var studentValues =
                student
                    .Split(',')
                    .Select(value => string.IsNullOrWhiteSpace(value) ? "0" : value);

            yield return string.Join(",", studentValues);
        }
    }
}