简体   繁体   中英

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.

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(' '));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM