例如,我有这个字符串“这是一个试用字符串”,并且我知道我想要位于位置 2 的单词(在本例中为单词“This”)。整个字符串索引 2 处的字母是单词“This”的一部分,所以我想得到那个单词。如果我提供分隔符的索引,那么我不会得到任何特定的单词,只是分隔符。
怎么能做到这一点?我找到了this链接,但它显示了如何在某个索引之后获取所有内容,我需要某个索引处的单词。
您可以创建一个检查空格的扩展方法:
像这样打电话: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);
}
}
我是一名优秀的程序员,十分优秀!