使用 indexof 方法定位单词在字符串中的起始索引,然后调用 substring 从该位置截取到末尾。如果未找到该单词,则返回原字符串或空值以避免异常。

IndexOf 匹配单词时是否区分大小写
默认情况下 IndexOf 是区分大小写的,这意味着 "Hello" 和 "hello" 会被视为不同的单词。如果需要不区分大小写的匹配,需要传入 StringComparison.OrdinalIgnoreCase 参数。

如何确保只截取完整的单词而不是子串
为了防止截取出类似 "app" 从 "apple" 中截取的错误情况,需要在查找前后检查边界字符是否为空格或标点符号,或者使用正则表达式进行更精确的匹配。
using System;
public class Program {
public static void Main() {
string text = "The quick brown fox jumps over the lazy dog.";
string target = "fox";
// 基础截取:从指定单词开始
int index = text.IndexOf(target);
if (index != -1) {
string result = text.Substring(index);
Console.WriteLine(result); // 输出: fox jumps over the lazy dog.
} else {
Console.WriteLine("Word not found");
}
}
}
预期结果:
输入: "The quick brown fox jumps over the lazy dog.", 目标: "fox"
输出: "fox jumps over the lazy dog."
using System;
public class Program {
public static void Main() {
string text = "The quick brown Fox jumps over the lazy dog.";
string target = "fox";
// 不区分大小写截取
int index = text.IndexOf(target, StringComparison.OrdinalIgnoreCase);
if (index != -1) {
string result = text.Substring(index);
Console.WriteLine(result); // 输出: Fox jumps over the lazy dog.
}
}
}
预期结果:
输入: "The quick brown Fox jumps over the lazy dog.", 目标: "fox"
输出: "Fox jumps over the lazy dog."
using System;
using System.Text.RegularExpressions;
public class Program {
public static void Main() {
string text = "I like apple and apples.";
string target = "apple";
// 使用正则表达式匹配完整单词
string pattern = $@"\b{Regex.Escape(target)}\b";
Match match = Regex.Match(text, pattern);
if (match.Success) {
string result = text.Substring(match.Index);
Console.WriteLine(result); // 输出: apple and apples.
}
}
}
预期结果:
输入: "I like apple and apples.", 目标: "apple"
输出: "apple and apples."











