c# 找到字符串中,固定字符串的位置
在 C# 中查找字符串中固定子字符串的位置,可以使用 IndexOf
、LastIndexOf
或正则表达式等方法。以下是具体实现和示例代码:
方法 1:使用 IndexOf
查找首个匹配位置
string mainString = "Hello World! Welcome to the World of C#."; string target = "World"; // 查找首个匹配位置(区分大小写) int firstIndex = mainString.IndexOf(target); Console.WriteLine($"首次出现位置: {firstIndex}"); // 输出: 6 // 忽略大小写查找 int firstIndexIgnoreCase = mainString.IndexOf(target, StringComparison.OrdinalIgnoreCase); Console.WriteLine($"首次出现位置(忽略大小写): {firstIndexIgnoreCase}");
方法 2:使用 LastIndexOf
查找最后一个匹配位置
int lastIndex = mainString.LastIndexOf(target);