Getting second word of a string in c#

16,094

Solution 1

You can do this. I suggest doing search before asking simple questions.

str.Split(' ')[1]

Demo code

Please note you have to include validations to your input, like string has more than one word, etc..

Solution 2

The simplest answer is to Split on space, and take the second item:

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

I use FirstOrDefault here so you get a valid null result for input of just one word.

The downside though is it will parse the entire string, so this is not a good suggestion if you want the second word of a book.


Or, you can make use of IndexOf to find the first and second occurrence of space, then Substring to take that portion:

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);
}

This only looks through as many characters as you need, then copies out the portion you want in the end. It will perform better than the above. But it probably doesn't matter unless you're cataloging the second word of every book ever published.


Or, do it the old-fashioned way. Go through each character until you find the first space, then keep characters until the next one or the end of the string:

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();

This method should be comparable in performance to the second one. You could accomplish the same thing using an enumerator instead of a foreach loop, but I'll leave that as an exercise for the reader. :)

Solution 3

This is the perfect answer I think

//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];
Share:
16,094
davz_11
Author by

davz_11

Updated on June 04, 2022

Comments

  • davz_11
    davz_11 almost 2 years

    I have declared a string and i want to get the second word from the string. For eg.

    string str = "Hello world";
    

    And I want to get the word "world" from str.