Skip to main content

We're continuing our C# tips and tricks and providing to you the snippet for getting the first word from a string.

/// <summary>
/// Method returns first word from passed string
/// </summary>
/// <param name="text">string for getting first word from</param>
/// <returns>string first word from passed string</returns>
public static string GetFirstWord(string text)
{
  string firstWord = String.Empty;
 
  // Check for empty string.
  if (String.IsNullOrEmpty(text))
  {
    return string.Empty;
  }
 
  // Get first word from passed string
  firstWord = text.Split(' ').FirstOrDefault();
  if (String.IsNullOrEmpty(firstWord))
  {
    return string.Empty;
  }
 
  return firstWord;
}

- Advertisement -
- Advertisement -