尝试拆分字符串时C#Null Reference Exception

时间:2014-05-30 20:17:56

标签: c# arrays string nullreferenceexception

我试图弄清楚如何在我的C#控制台应用程序中解决NullReferenceException。

它处于基础水平。

基本上,我有一个名为getWord()的方法。它需要两个参数 - 一个字符串和一个整数。

getWord使用整数并根据字符串中的整数获取单词(基于空格,无逗号或任何其他类型的标点符号)

它应该如何运作:

getWord(" john是17岁",0)导致" john"

getWord(" john是17岁",1)结果"是"

getWord(" john是17岁",2)导致" 17岁"

在程序中,我声明一个简单的字符串数组,初始化它,并向其添加两个元素。

我循环遍历数组的每个元素,并从数组的每个元素打印第一个单词 - getWord(line,0)。

问题是控制台打印每行的第一个单词但在此之后我在这一行得到NullReferenceException:

    string[] words = inputString.Split(new char[] { ' ' });

我不知道为什么。如果重要的话,我使用的是Visual C#2008和.NET Framework 3.5。 我一直在我的所有C#代码中获得NullReferenceExceptions,我不知道为什么。

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

    namespace ConsoleApplication1
    {
        class Program
        {
            public static string[] levelCurList;
            static void Main(string[] args)
            {

                levelCurList = new string[500];

                levelCurList[0] = "52 afdaf";
                levelCurList[1] = "dfsf afdf";

                foreach (string line in levelCurList)
                {
                    Console.WriteLine(getWord(line, 0));
                }

            }
            public static string getWord(string inputString, int word)
            {
                string[] words = inputString.Split(new char[] { ' ' });
                if (words.Length >= word)
                    return words[word];  
                else
                    return "";
            }
        }
    }

1 个答案:

答案 0 :(得分:3)

将新string[500]更改为new string[2],您的数组中有500个元素,只初始化其中两个元素,其余部分为 null 。< / p>

您正在将 null 字符串传递给getWord方法,这就是您获得异常的原因。您还可以使用:

foreach (string line in levelCurList.Take(2))

或者:

foreach (string line in levelCurList.Where(x => x != null))

注意:您还应将if (words.Length >= word)更改为if (words.Length > word)(删除=),否则当IndexOutOfRange参数等于word时,您将获得words.Length例外words[words.Length - 1];。由于数组索引为零,因此字符串的最后一个元素是words[words.Length];而不是{{1}}

相关问题