Учитывая конкретный порядковый номер строки, как я могу получить полное слово в C #? - PullRequest
1 голос
/ 09 января 2012

Например, у меня есть эта строка «Это пробная строка», и я знаю, что хочу слово, которое находится в позиции 2 (в данном случае, слово «Это»). Буква в индексе 2 всей строки является частью слова «Это», поэтому я хочу получить это слово. Если я укажу индекс разделителя, я не получу никакого конкретного слова, только разделитель.

Как это можно сделать? Я нашел эту ссылку, но она показывает, как получить все ПОСЛЕ определенного индекса, мне нужно слово AT для определенного индекса.

Ответы [ 10 ]

4 голосов
/ 09 января 2012

Вы можете создать метод расширения, который проверяет пробелы:

Вызовите так: 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);

        }
    }
2 голосов
/ 09 января 2012

Используйте RegEx и Linq, чтобы получить слова и найти слово (например, Match), где начальный индекс и длина ограничивают позицию вашего персонажа:

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;
}
2 голосов
/ 09 января 2012

Вы можете хранить начальные индексы слов в массиве (или хеш-таблице), например:

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 будет содержать все индексы.

1 голос
/ 09 января 2012

как насчет (не проверено и не оптимизировано) ...

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 и настроить соответственно

1 голос
/ 09 января 2012
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);
1 голос
/ 09 января 2012

Чтобы найти слово в позиции символа, вы можете сделать это:

        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;

Возвращает слово после пробела, если индекс соответствует пробелу.

0 голосов
/ 09 января 2012

Я думаю, что это одно из самых быстрых решений

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
        }
0 голосов
/ 09 января 2012

Нечто подобное должно работать на вас.

    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);
0 голосов
/ 09 января 2012

Вот простая версия:

var firstPos = str.LastIndexOf(' ', index) + 1;
var lastPos = str.IndexOf(' ', index);
var word = lastPos == -1 ? str.Substring(firstPos)
                         : str.Substring(firstPos, lastPos - firstPos);
0 голосов
/ 09 января 2012
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);
...