user13310388
user13310388

Reputation:

Adding words from string to list c#

I am having trouble adding words from a string to my list.

List<string> list = new List<string>();

string StringSorter = "Hello I like C#";

            for (int i = 0; i < StringSorter.Length; i++)
            {
                string[] splitter = StringSorter.Split(" ");
                list.Add(splitter[i]);
            }

I want every word to be in an index in the list. And it works until the end of the string is reached where it crashes and it says "Index was outside the bounds of the array". I simply can't figure out how to fix this issue.

Upvotes: 1

Views: 2800

Answers (1)

Olli
Olli

Reputation: 676

Your problem is, that you iterate over each character inside your string and try to split the string for each iteration.

You only have to split your string once.

You could do it like this:

string myString = "Hello I like C#";
List<string> list = new List<string>();

string[] splittedStringArray = myString.Split(' ');

foreach (string stringInArray in splittedStringArray) {
    list.Add(stringInArray);
}

As already mentioned in the comments you could use the linq extension method ToList() to cast the returning array of your Split Function directly to a List like this:

string myString = "Hello I like C#";

List<string> list = myString.Split(' ').ToList(); 

One more thing you can do is to use the AddRange() function of your list. So you have no need to cast your returning array to a list. This will also make it easier if you want to do this many times:

string myStringOne = "Hello I like C#";
string myStringTwo = "I copied the top comment for my answere";

List<string> list = new List<string>();

list.AddRange(myStringOne.Split(' '));
list.AddRange(myStringTwo.Split(' '));

Upvotes: 1

Related Questions