First Word of a string in C#

Viewed 919

How do I get the first word of a string.

string test = "hello, world"

I used test.Split(' ').FirstOrDefault() but it returns "hello,"

I could try by adding the separator as comma but even if there is comma or space, I need just the word 'hello'. I mean if string test = "hello world" then also it should return "hello"

3 Answers

If you only want to have the A-Z or a-z letters in the string, use regex to remove everything else, then split the string.

Regex.Replace(str, "[^a-zA-Z0-9]", String.Empty).Split(' ').FirstOrDefault() should do the trick.

Regex is the way !!!

Try following code:

string pattern = @"^\w+";
string test = "hello, world";
var firstWord = Regex.Match(test, pattern);
Console.WriteLine(firstWord);

// output
// hello

Don't forget to include namespace 'System.Text.RegularExpressions'

I think you could use something like the Char class, it's easier to undertsand.

for example:

string test = "Hello, world!";

string split = test.Split(' ')[0];           //Split by space
if (!Char.IsLetter(split.Last()))            //Check if last character is letter
    split = split.Remove(split.Length - 1);  //If not, remove last character
    
Console.WriteLine(split);                    //Print out the word
Related