indexof 默认区分大小写,要查找大小写不同的关键字,需要传入 stringcomparison.ordinalignorecase 参数。在 .net core 2.0+ 或 .net standard 2.1+ 中,可以直接使用重载方法 indexof(string value, stringcomparison comparisontype)。这样做会忽略大小写差异,返回第一个匹配项的索引,若未找到则返回 -1。

如何验证忽略大小写的搜索行为?
通过调用带 StringComparison 参数的 IndexOf 方法,可以确认搜索是否忽略大小写。例如,在字符串 "Hello World" 中查找 "hello",使用 OrdinalIgnoreCase 会返回 0,而默认行为返回 -1。

using System;
class Program
{
static void Main()
{
string text = "Hello World";
string keyword = "hello";
// 默认区分大小写
int indexDefault = text.IndexOf(keyword);
Console.WriteLine($"Default: {indexDefault}"); // Output: -1
// 忽略大小写
int indexIgnoreCase = text.IndexOf(keyword, StringComparison.OrdinalIgnoreCase);
Console.WriteLine($"IgnoreCase: {indexIgnoreCase}"); // Output: 0
}
}
如何处理多关键字的大小写不敏感搜索?
当需要搜索多个关键字时,可以遍历关键字列表,对每个关键字使用 IndexOf 并指定 StringComparison.OrdinalIgnoreCase。这样可以确保无论关键字的大小写形式如何,都能正确找到匹配项。

using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
string text = "Hello World, Hello C#";
List<string> keywords = new List<string> { "hello", "WORLD", "c#" };
foreach (string keyword in keywords)
{
int index = text.IndexOf(keyword, StringComparison.OrdinalIgnoreCase);
if (index != -1)
{
Console.WriteLine($"Found '{keyword}' at index {index}");
}
else
{
Console.WriteLine($"'{keyword}' not found");
}
}
}
}</string></string>
基于程序中某个输入、条件或结果的具体问题
在上面的代码中,如果输入文本为空字符串,IndexOf 的行为取决于关键字是否为空。如果关键字也为空,IndexOf 返回 0;如果关键字非空,返回 -1。这是因为空字符串被视为在任何位置都匹配。在实际应用中,需要处理这种边界情况,以避免意外的匹配结果。











