gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 17:33:54 25 4
gpt4 key购买 nike

例如,我有这个字符串“这是一个试用字符串”,并且我知道我想要位于位置 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);

}
}

关于c# - 给定字符串的特定索引号,如何在 C# 中获取完整的单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8789067/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com