views:

109

answers:

7

Hi,

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

Basically if the string is hello word... I need to get hello...

Thanks

+5  A: 
var s = "Hello World";
var firstWord = s.SubString(0,s.IndexOf(" "));
Jamiec
I would add a special case for if the string contains only one word, e.g. if **IndexOf** returns -1.
Paul Ruane
@Paul - scope creep :) The question never specified that, nor using other whitespace.
Jamiec
@Jawiec: Poppycock. The question said "What's the best way to return the first word of a string in C#?" so it should be able to handle any string. Your code would barf with an empty string, or with a string containing one word. (It also only handles one flavour of whitespace, but that is nitpicking.)
Paul Ruane
A: 
string words = "hello world";
string [] split = words.Split(new Char [] {' '});
if(split.Lenght >0){
 string first = split[0];
}
Arseny
+5  A: 

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
+7  A: 

You can try:

string s = "Hello World";
string firstWord = s.Split(' ').FirstOrDefault();
ppolyzos
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
+1  A: 

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...

Vilx-
+1  A: 

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
A: 

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