如何使用算法从我的列表中删除一个单词



我正在做一个项目,需要帮助了解如何从列表中删除一个单词。我有很多场景要做,这就是其中之一。我必须实现一个.DeleteWord("hello"(函数。有什么想法吗?这是我的密码。

static void Main(string[] args)
{
List<string> words = new List<string>();
words.Add("car");
words.Add("caramael");
words.Add("hey");
words.Add("hello");
words.Add("helloeverybody");
words.Add("CSC204");
// Console.WriteLine("Scenario 1:");
// Console.WriteLine();
// foreach (string word in words)
// {
//      Console.WriteLine(word);
//  }
foreach (string word in words.GetWordsForPrefix("he"))
{
Console.WriteLine(word);
}
Console.WriteLine("nScenario 5 Printing all words:");
words.Sort();
Console.WriteLine();
foreach (string word in words)
{
Console.WriteLine(word);
}
Console.WriteLine("n Scenario 6 Insert  "car":");
int index = words.BinarySearch("car");
if (index < 0)
{
words.Insert(~index, "car");
}
Console.WriteLine();
foreach (string word in words)
{
Console.WriteLine("Error, This word already exsits");
}
}

我必须实现一个.DeleteWord("hello"(函数。

据我所知,您需要一个函数,如果列表中已经存在某个元素,则该函数可以从列表中删除该元素。以下是用于此目的的代码片段:

public static void RemoveWord(List<string> wordList, string word)
{
wordList.Remove(word);
}

如果不允许使用内置函数,可以循环浏览列表并删除所需项。有一个陷阱你必须避免:当删除一个项目时,以下项目的索引和列表计数将减少1。因此,最好向后循环。

for (int i = list.Count - 1; i >= 0; i--) {
if (list[i] meets some condition) {
list.RemoveAt(i);
}
}

如果你只想删除第一次出现的内容,你可以用break离开循环,不必关心这个索引问题,你可以循环转发

for (int i = 0; i < list.Count; i++) {
if (list[i] meets some condition) {
list.RemoveAt(i);
break;
}
}

最新更新