简体   繁体   中英

How to take n part of String using Split() method in C#?

I have string str = "Join Smith hate meat" .

I want to get JoinSmith from this str .

I tried code:

private static string GetFirstWord(string str)
{
    return str.Split(' ').Take(2).ToString();
}

This code not working for me.

I tried: return str.Split(' ').FirstOrDefault it get only first part of string Join .

采用

string result = string.Concat(str.Split(' ').Take(2)); // "JoinSmith"

A Fancy combination:

var result = string.Join(String.Empty, str.Split(' ').Take(2));

Takes the first two words, joins them into one string.

Or:

var result = string.Concat(str.Split(' ').Take(2));

Something a little different

var result = new string(TakeAllUntilSecondSpace(str).ToArray());

Yield the characters you want... sometimes this is a good way if you need a lot of control that standard methods don't provide.

private IEnumerable<char> TakeAllUntilSecondSpace(string s)
{
    var spaceEncountered = false;
    foreach (char c in s)
    {
        if (c == ' ')
        {
            if (spaceEncountered) yield break;
            spaceEncountered = true;
        } else yield return c;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM