如何在C#博客控制台应用中实现正确的线性搜索方法?
修正C#博客搜索方法的问题
你写的搜索方法存在几个明显错误,直接修正如下:
错误点说明
- 返回值类型不匹配:方法声明返回
string,但你实际要返回索引(整数),类型冲突 - 循环条件错误:
i < myBlog是把List对象和整数比较,应该用myBlog.Count获取列表元素总数 - 返回值与声明类型不符:返回的
i是整数,和string类型不兼容
正确的搜索方法实现
static int BlogSearch(List<string[]> myBlog, string searchedWord) { for (int i = 0; i < myBlog.Count; i++) { // 不区分大小写比较标题,用StringComparison更规范 if (searchedWord.Equals(myBlog[i][0], StringComparison.OrdinalIgnoreCase)) { return i; // 返回第一个匹配帖子的索引 } } return -1; // 未找到时返回-1 }
调用方法替换原代码
把原来case 3里的搜索逻辑换成下面的代码:
case 3: Console.Write("请输入要搜索的帖子标题: "); string searchedWord = Console.ReadLine(); int foundIndex = BlogSearch(myBlog, searchedWord); if (foundIndex != -1) { Console.WriteLine("\n您查找的帖子存在于博客中:"); Console.WriteLine("\n标题: " + myBlog[foundIndex][0] + "\n内容: " + myBlog[foundIndex][1] + "\n\n按回车键返回菜单..."); } else { Console.WriteLine("未找到匹配的帖子。按回车键返回菜单..."); } Console.ReadLine(); // 等待用户输入回车 break;
如果需要查找所有匹配的帖子(而不是第一个),可以把方法改成返回匹配索引的列表:
static List<int> BlogSearchAll(List<string[]> myBlog, string searchedWord) { List<int> matchedIndices = new List<int>(); for (int i = 0; i < myBlog.Count; i++) { if (searchedWord.Equals(myBlog[i][0], StringComparison.OrdinalIgnoreCase)) { matchedIndices.Add(i); } } return matchedIndices; }
调用时遍历返回的索引列表输出所有匹配内容即可。
内容的提问来源于stack exchange,提问作者sam_the_man
相关产品推荐
相关产品推荐

