如果单词之间有更多空格,如何从字符串中获取第n个单词?

时间:2018-10-05 09:55:42

标签: c# string if-statement

我正在尝试从这样的句子中打印出第x个单词:

string phrase = Console.ReadLine();
int wordIndex = Convert.ToInt32(Console.ReadLine());
string currentWord = "";
int currentWordIndex = 1;

for (int i = 0;  i < phrase.Length; i++)
{
if (phrase[i] != ' ')
    currentWord += phrase[i];

if (phrase[i] == ' ' || i == phrase.Length - 1)
{
    if (wordIndex == currentWordIndex)
    {
        Console.WriteLine(currentWord);
        break;
    }

    currentWord = "";

    if (i != phrase.Length - 1)
        currentWordIndex++;
 }

}

if (wordIndex > currentWordIndex)
Console.WriteLine("N/A");

即使单词之间有更多空格,我也希望它能正常工作。有什么帮助吗?

3 个答案:

答案 0 :(得分:4)

string[] splited = phrase.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
string nth = splited.Length >= n ? splited[n-1] : "N/A";
Console.WriteLine(nth);

答案 1 :(得分:2)

using System;
using System.Linq; // !! important

public class Program
{
    public static void Main()
    {
        string phrase = Console.ReadLine();
        int wordIndex = Convert.ToInt32(Console.ReadLine());
        var result = phrase.Split(new []{' '}, StringSplitOptions.RemoveEmptyEntries)
            .Skip(wordIndex - 1)
            .FirstOrDefault(); 
        Console.WriteLine(result ?? "N/A");
    }
}

输出:

>hello, this is a test
>3
is

另一个选项,相同的结果

var result = phrase.Split()
    .Where(x => !string.IsNullOrWhiteSpace(x))
    .Skip(wordIndex - 1)
    .FirstOrDefault(); 

答案 2 :(得分:1)

您只需清除双精度空格:while (phrase.IndexOf(" ") != -1) phrase = phrase.Replace(" ", " ");。如果单词之间有4个以上的空格,则需要while循环。使用SplitRemoveEmptyEntries的解决方案更好,我的答案是另一种解决方案。