给定一个字符串的特定索引号,如何在 C# 中获取完整的单词?

Sop*_*oph 2 .net c# string

例如,我有这个字符串“这是一个试验字符串”,并且我知道我想要位置 2 处的单词(在本例中为单词“This”)。整个字符串索引 2 处的字母是单词“This”的一部分,所以我想获取该单词。如果我提供分隔符的索引,那么我不会得到任何特定的单词,而只是分隔符。

\n\n

怎么能做到这一点呢?我找到了这个链接,但它显示了如何在某个索引之后获取所有内容,我需要单词“AT”某个索引。

\n

Bas*_*Bas 5

您可以创建一个检查空格的扩展方法:

像这样调用: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)