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
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
var s = "Hello World";
var firstWord = s.SubString(0,s.IndexOf(" "));
string words = "hello world";
string [] split = words.Split(new Char [] {' '});
if(split.Lenght >0){
string first = split[0];
}
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;
You can try:
string s = "Hello World";
string firstWord = s.Split(' ').FirstOrDefault();
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...
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];
}
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();
}