left string function in C#

Viewed 61626

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

9 Answers

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;
        }
    }
Related