Micky
Micky

Reputation: 25

Parsing input string and adding to dictionary

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?

Upvotes: 0

Views: 2996

Answers (2)

King King
King King

Reputation: 63357

You don't need such many loops here, just pass in the key, if it exists, the value will be updated, otherwise the new entry will be added:

userInput = Console.ReadLine();
var matches = Regex.Matches(userInput,@"\w+\s+\w+");
foreach(Match m in matches){
  if(m.Success){
    var w = m.Value.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
    dict[w[0]] = w[1];
  }
}

Note that, the code doesn't check for invalid input from user. All the input should be like this:

word1 value1 word2 value2 word3 value3 ...
//after collecting matches, we will the following matches:
word1 value1
word2 value2
word3 value3
...

Upvotes: 0

Kamil Budziewski
Kamil Budziewski

Reputation: 23107

 for (int j = 0; j < wordbits.Length; j++)
 {
     val = wordbits[(j + 1)];
 }

this won't work, you can change to:

 for (int j = 0; j < wordbits.Length-1; j++)
 {
     val = wordbits[(j + 1)];
 }

or just change (but this will change logic):

 val = wordbits[j];

because you are in last iteration accessing wordbits[wordbits.Length] you are getting exception, arrays are indexed from 0 to length-1

EDIT:

ok, I get it, you are getting values like: key value key value key value, change your logic to:

    for (int i = 0; i < wordbits.Length-1; i+=2)
    {
        key = wordbits[i];
        val = wordbits[(i + 1)];

        dict.Add(key, val);
    }

it will add keys and values to your dictionary. In your logic inner for is looping through all values of wordbits again, so it won't work, for loop is not needed there.

Upvotes: 1

Related Questions