Some Background:
I'm currently learning C# and working on a ChatBot project. The Chatbot will learn from user input, by parsing each user inputted sentence, and placing each word into a dictionary with each word in the sentence as the key and the word that follows it as a value in the dictionary.
My First stumbling block is trying to loop through the string to place the words into the dictionary.
My Code:
class Program
{
static string userInput;
static string val;
static string key;
static Dictionary<string, string> dict = new Dictionary<string, string>();
static void Main(string[] args)
{
userInput = Console.ReadLine();
string[] wordbits = userInput.Split(' ');
for (int i = 0; i < wordbits.Length; i++)
{
key = wordbits[i];
for (int j = 0; j < wordbits.Length; j++)
{
val = wordbits[(j + 1)];
}
dict.Add(key, val);
}
}
}
The error I'm getting with this is IndexOutOfRangeException, which I assume is because the loop is looking for a word after the last word in the sentence, that doesn't exist.
Any suggestions on how to fix this?
wordbits.ToDictionary(x => x, x => wordbits[wordbits.Length - 1])but I'm not sure you're after that. Or justwordbits.ToDictionary(x => x, x => wordbits.Last())