vendredi 30 mai 2014

C# Null Reference Exception while trying to split a string


Vote count:

0




I'm trying to figure out how to resolve a NullReferenceException in my C# console application.


It's at a basic level.


Essentially, I have a method called getWord(). It takes two arguments- a string and an integer.


getWord uses the integer and gets the word based on that integer from the string(based on spaces, no commas or any other types of punctuation)


This is how it is supposed to work:


getWord("john is seventeen", 0) results in "john"


getWord("john is seventeen", 1) results in "is"


getWord("john is seventeen", 2) results in "seventeen"


In the program, I declare a simple string array, initialize it, and add two elements to it.


I loop through each element of the array and print the first word from each element of the array - getWord(line, 0).


The problem is that the console prints the first word of each line but after that I get a NullReferenceException on this line:



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


And I have no clue why. I'm using Visual C# 2008 and .NET Framework 3.5 if it matters. I keep getting NullReferenceExceptions in all of my C# code and I have no idea why.



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 "";
}
}
}


asked 35 secs ago






Aucun commentaire:

Enregistrer un commentaire