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

时间:2012-01-09 13:22:03

标签: c# .net string

例如,我有这个字符串“这是一个试用字符串”,我知道我想要位于第2位的单词(在这种情况下,单词“This”)。整个字符串的索引2处的字母是“This”一词的一部分,所以我想得到那个词。如果我提供了分隔符的索引,那么我就不会得到任何特定的单词,只有分隔符。

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

10 个答案:

答案 0 :(得分:4)

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

这样打电话: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);

        }
    }

答案 1 :(得分:2)

您可以将单词的起始索引存储在数组(或哈希表)中,例如:

0 : The
6 : is
9: a
11: trial
17: string

然后将其与您需要的索引进行比较。

<强> UPD。添加查找索引的示例:

static void Main(string[] args)
{
    var str = "This is a trial string";
    var words = str.Split(new [] { " " }, StringSplitOptions.RemoveEmptyEntries);
    var list = new List<Tuple<int, string>>();
    foreach (var word in words)
    {
        list.Add(new Tuple<int, string>(str.IndexOf(word), word));
    }
}

变量list将包含所有索引。

答案 2 :(得分:2)

使用RegEx和Linq获取单词,并找到开头索引和长度绑定角色位置的单词(即匹配):

static string GetWord(String input, int charIndex) {
    if (charIndex > (input.Length - 1)) { throw new IndexOutOfRangeException(); }
    if (!Regex.IsMatch(input[charIndex].ToString(), @"\w")) {
        throw new ArgumentException(
            String.Format("The character at position {0} is not in a word", charIndex));
    }
    return (
        from Match mx in Regex.Matches(input, @"\w+")
        where (mx.Index <= charIndex) && ((mx.Index + mx.Length - 1) >= charIndex)
        select mx).Single().Value;
}

答案 3 :(得分:1)

要在字符位置找到单词,您可以执行以下操作:

        string input = "This is a trial string";
        int position = 2;

        var words = input.Split(' ');

        int characterCount = 0;
        for (int wordIndex = 0; wordIndex < words.Length; wordIndex++)
        {
            var word = words[wordIndex];
            if (characterCount + word.Length + wordIndex > position)
                return word;
            characterCount += word.Length;
        }

        return null;

如果索引对应于空格,则返回空格后面的单词。

答案 4 :(得分:1)

string sString = "This is a trial string";
int iPos = 3;
int iBegin = -1, iEnd = 0;

if (sString[iPos] == ' ') // Character is space, no word?
    return;

for (int i = iPos; i >= 0; i--)
    if (sString[i] == ' ')
    {
       iBegin = i+1;
       break;
    }

if (iBegin == -1) // in case of first word
    iBegin = 0;

for (int i = iPos; i < sString.Length; i++)
    if (sString[i] == ' ') 
    {
        iEnd = i-1;
        break;
    }

string sWord = sString.Substring(iBegin, iEnd-iBegin+1);

答案 5 :(得分:1)

如何(未经测试和未经优化)...

string GetWordAtIndex(string original, int position)
{
    int startPoint = original.Substring(0,position).LastIndexOf(" ");
    if(startPoint < 0) startPoint = 0;
    int endPoint = original.Substring(position).IndexOf(" ") + position;
    return original.Substring(startPoint, endPoint-startPoint);
}

也不会检查原始字符串中的最后一个单词,这可能会导致越界错误。只需检查endPoint == -1并进行相应调整

答案 6 :(得分:0)

string WordAtIndex( string myString, int chosenIndex)
{
     char[] cArray = myString.ToCharArray();

     int currentWordCount = 0;

     //return an empty string if the index is whitespace.
     if (cArray[chosenIndex] == ' ')
         return string.Empty;

     for (int i = 0; i < chosenIndex; i++)
     {
         if (cArray[i] == ' ')
             currentWordCount++;
     }

     return myString.Split(' ')[currentWordCount];
}

使用:

string word = WordAtIndex("This is a trial string", 2);

答案 7 :(得分:0)

这是一个简单的版本:

var firstPos = str.LastIndexOf(' ', index) + 1;
var lastPos = str.IndexOf(' ', index);
var word = lastPos == -1 ? str.Substring(firstPos)
                         : str.Substring(firstPos, lastPos - firstPos);

答案 8 :(得分:0)

这样的事情对你有用。

    string GetWordFromIndex(string value, int index)
    {

        int scannedIndex = 0;
        return  value.Split().First<string>(str =>
        {

            scannedIndex += str.Length;
            if (index < scannedIndex)
            {
                return true;
            }

            return false;

        });

    }

使用

var result = GetWordFromIndex( "This is a trial string", 2);

答案 9 :(得分:0)

我认为这是最快的解决方案之一

public static string GetWord(string str,int index) {
            var vettWord = str.Split(' ');
            int position=0;
            foreach(var item in vettWord){
                if ( index<= position+item.Length)
                {
                    return item;
                }
               position += item.Length+1; // +1 to consider the white space
            }
            return string.Empty;
        }

我试过了

  static void Main(string[] args)
        {

            string s = "This is a trial string";
            Console.WriteLine(GetWord(s, 17)); //string
            Console.WriteLine(GetWord(s, 2)); // This
            Console.WriteLine(GetWord(s, 9)); // a
        }