2

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.

Ave
  • 4,338
  • 4
  • 40
  • 67

3 Answers3

5

Use

string result = string.Concat(str.Split(' ').Take(2)); // "JoinSmith"
fubo
  • 44,811
  • 17
  • 103
  • 137
  • 2
    SO is not a competition between the users. I think it should be a competition between the answers. So that someone who searches for a solution gets the best by choosing the answer with the most votes. And in this case `string.Concat` should be used over `strign.Join` http://stackoverflow.com/a/12257751/1315444 – fubo Jul 14 '16 at 06:28
  • I up-vote your answer. I think @user3185569 reply before your answer and it working. After, he was updated the answer. – Ave Jul 14 '16 at 07:30
  • 1
    @VănLộc both answers are working. `string.Concat()` is the better solution in this case (performance and readability). By copying my answer into his, my answer got obsolete. Imo that's not how it should be done. – fubo Jul 14 '16 at 07:34
1

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));
Zein Makki
  • 29,485
  • 6
  • 52
  • 63
1

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;
    }
}
CRice
  • 12,279
  • 7
  • 57
  • 84