您可以创建一个检查空格的扩展方法:
像这样调用:string theWord = myString.GetWordAtPosition(18);
static class WordFinder
{
public static string GetWordAtPosition(this string text, int position)
{
if (text.Length - 1 < position || text[position] == ' ') return null;
int start = position;
int end = position;
while (text[start] != ' ' && start > 0) start--;
while (text[end] != ' ' && end < text.Length - 1) end++;
return text.Substring(start == 0 ? 0 : start + 1, end - start - 1);
}
}
Run Code Online (Sandbox Code Playgroud)