【问题标题】:Getting second word of a string in c# [duplicate]在c#中获取字符串的第二个单词[重复]
【发布时间】:2016-01-14 06:10:21
【问题描述】:

我已经声明了一个字符串,我想从字符串中获取第二个单词。例如。

string str = "Hello world";

我想从str中得到“世界”这个词。

【问题讨论】:

  • var a = str.Split(' ').Last();
  • 这很简单,所以我建议您首先阅读有关您选择的编程语言的书籍。你可以使用Split函数来实现你想要的。

标签: c# string substring


【解决方案1】:

最简单的答案是Split上空间,取第二项:

var secondWord = str.Split(' ').Skip(1).FirstOrDefault();

我在这里使用FirstOrDefault,因此您只需输入一个单词即可获得有效的null 结果。

缺点是它会解析整个字符串,所以如果你想要一本书的第二个单词,这不是一个好建议。


或者,您可以使用IndexOf 查找第一次和第二次出现的空格,然后Substring 获取该部分:

static string GetSecondWord(string str)
{
    var startIndex = str.IndexOf(' ') + 1;
    if (startIndex == 0 || startIndex == str.Length)
        return null;

    var endIndex = str.IndexOf(" ", startIndex, StringComparison.CurrentCulture);
    if (endIndex == -1)
        endIndex = str.Length - 1;
    return str.Substring(startIndex, endIndex - startIndex + 1);
}

这只会查看您需要的字符数,然后最后复制出您想要的部分。它会比上面的表现更好。但这可能无关紧要,除非您对每本书的第二个单词进行编目。


或者,用老式的方式来做。遍历每个字符,直到找到第一个空格,然后保留字符直到下一个字符或字符串末尾:

var sb = new StringBuilder();

bool spaceFound = false;

foreach(var c in str)
{
    if(c == ' ')
    {
        if (spaceFound) //this is our second space so we're done
            break;

        spaceFound = true;
    }
    else
    {
        if (!spaceFound) //we haven't found a space yet so move along
            continue;

        sb.Append(c);
    }
}

var secondWord = sb.ToString();

此方法的性能应该与第二种方法相当。您可以使用枚举器而不是 foreach 循环来完成同样的事情,但我将把它作为练习留给读者。 :)

【讨论】:

    【解决方案2】:

    你可以这样做。我建议在问简单问题之前先进行搜索。

    str.Split(' ')[1]
    

    Demo code

    请注意,您必须在输入中包含验证,例如字符串包含多个单词等。

    【讨论】:

    • 如果输入字符串是单个单词会抛出Index out of range exception
    • 确实如此,但让用户处理此类边界情况。无论如何,我会将这一点作为答案的一部分。谢谢@un-lucky
    【解决方案3】:

    这是我认为的完美答案

    //single space(or)
     string line = "Hello world";
    //double space(or)
    string line = "Hello  world";
    //multiple space(or)
    string line = "Hello     world";
    //multiple Strings
    string line = "Hello world Hello  world";
    //all are working fine
    
                string[] allId = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                string finalstr = allId[allId.Length-1];
    

    【讨论】:

    • 为什么你认为这是完美的答案?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 2011-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-04
    • 1970-01-01
    相关资源
    最近更新 更多