23

What's the best way to return the first word of a string in C#?

Basically if the string is "hello world", I need to get "hello".

Thanks

jwg
  • 5,547
  • 3
  • 43
  • 57
D_D
  • 1,019
  • 4
  • 15
  • 25

9 Answers9

57

You can try:

string s = "Hello World";
string firstWord = s.Split(' ').First();

Ohad Schneider's comment is right, so you can simply ask for the First() element as there will always be at least one element.

For further info on whether to use First() or FirstOrDefault() you can learn more here

Community
  • 1
  • 1
ppolyzos
  • 6,791
  • 6
  • 31
  • 40
  • 7
    Slight improvement: use the overload for `String.Split` that takes a maximum splits count as you don't care about all but the first section. – Richard Aug 31 '10 at 09:11
  • 3
    You don't need `FirstOrDefault`, there will always be at least one element so you can just write `First` (even if there's no space you'll get the entire string). – Ohad Schneider Mar 30 '15 at 15:23
  • Your solution is correct, there's no need to "try". – Heinzi Oct 15 '17 at 15:47
  • 1
    Why involve Linq at all? If there will always be an element and you are using first, just access it via the indexer: `string firstWord = s.Split(' ')[0];` – Stephen P. Nov 19 '18 at 18:00
  • 2
    Notice that the maximum split parts (if used) should be 2 and not 1: theString.Split(new char []{ ' ', '\t'}, 2).First(); – ed22 Nov 22 '19 at 13:51
28

You can use a combination of Substring and IndexOf.

var s = "Hello World";
var firstWord = s.Substring(0,s.IndexOf(" "));

However, this will not give the expected word if the input string only has one word, so a special case is needed.

var s = "Hello";
var firstWord = s.IndexOf(" ") > -1 
                  ? s.Substring(0,s.IndexOf(" "))
                  : s;
Jamiec
  • 133,658
  • 13
  • 134
  • 193
8

One way is to look for a space in the string, and use the position of the space to get the first word:

int index = s.IndexOf(' ');
if (index != -1) {
  s = s.Substring(0, index);
}

Another way is to use a regular expression to look for a word boundary:

s = Regex.Match(s, @"(.+?)\b").Groups[1].Value;
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
3

The answer of Jamiec is the most efficient if you want to split only on spaces. But, just for the sake of variety, here's another version:

var  FirstWord = "Hello World".Split(null, StringSplitOptions.RemoveEmptyEntries)[0];

As a bonus this will also recognize all kinds of exotic whitespace characters and will ignore multiple consecutive whitespace characters (in effect it will trim the leading/trailing whitespace from the result).

Note that it will count symbols as letters too, so if your string is Hello, world!, it will return Hello,. If you don't need that, then pass an array of delimiter characters in the first parameter.

But if you want it to be 100% foolproof in every language of the world, then it's going to get tough...

Community
  • 1
  • 1
Vilx-
  • 104,512
  • 87
  • 279
  • 422
2

Shamelessly stolen from the msdn site (http://msdn.microsoft.com/en-us/library/b873y76a.aspx)

string words = "This is a list of words, with: a bit of punctuation" +
    "\tand a tab character.";

string [] split = words.Split(new Char [] {' ', ',', '.', ':', '\t' });

if( split.Length > 0 )
{
    return split[0];
}
TK.
  • 46,577
  • 46
  • 119
  • 147
1

Instead of doing Split for all the string, Limit your Split to count of 2. Use the overload which takes count as parameter as well. Use String.Split Method (Char[], Int32)

string str = "hello world";
string firstWord = str.Split(new[]{' '} , 2).First();

Split will always return an array with at least one element so either .[0] or First is enough.

Habib
  • 219,104
  • 29
  • 407
  • 436
1

Handles the various different whitespace characters, empty string and string of single word.

private static string FirstWord(string text)
{
    if (text == null) throw new ArgumentNullException("text");

    var builder = new StringBuilder();

    for (int index = 0; index < text.Length; index += 1)
    {
        char ch = text[index];
        if (Char.IsWhiteSpace(ch)) break;

        builder.Append(ch);
    }

    return builder.ToString();
}
Paul Ruane
  • 37,459
  • 12
  • 63
  • 82
0
string words = "hello world";
string [] split = words.Split(new Char [] {' '});
if(split.Length >0){
 string first = split[0];
}
Arseny
  • 7,251
  • 4
  • 37
  • 52
0

I used this function in my code. It provides an option to either uppercase the first word or every single word.

        public static string FirstCharToUpper(string text, bool firstWordOnly = true)
    {
        try
        {
            if (string.IsNullOrEmpty(text))
            {
                return text;
            }
            else
            {
                if (firstWordOnly)
                {
                    string[] words = text.Split(' ');
                    string firstWord = words.First();
                    firstWord = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(firstWord.ToLower());
                    words[0] = firstWord;
                    return string.Join(" ", words);
                }
                else
                {
                    return System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(text.ToLower());
                }
            }
        } catch (Exception ex)
        {
            Log.Exc(ex);
            return text;
        }
    }
gabics
  • 250
  • 1
  • 14