.NET method to convert a string to sentence case

后端 未结 9 1704
一向
一向 2020-11-30 09:47

I\'m looking for a function to convert a string of text that is in UpperCase to SentenceCase. All the examples I can find turn the text into TitleCase.

<
相关标签:
9条回答
  • 2020-11-30 10:19

    I found this sample on MSDN.

    0 讨论(0)
  • 2020-11-30 10:23

    This works for me.

    /// <summary>
    /// Converts a string to sentence case.
    /// </summary>
    /// <param name="input">The string to convert.</param>
    /// <returns>A string</returns>
    public static string SentenceCase(string input)
    {
        if (input.Length < 1)
            return input;
    
        string sentence = input.ToLower();
        return sentence[0].ToString().ToUpper() +
           sentence.Substring(1);
    }
    
    0 讨论(0)
  • 2020-11-30 10:33

    If you'd like to sentence case a string containing punctuation other than just periods:

    string input = "THIS IS YELLING! WHY ARE WE YELLING? BECAUSE WE CAN. THAT IS ALL.";
    var sentenceRegex = new Regex(@"(^[a-z])|[?!.:,;]\s+(.)", RegexOptions.ExplicitCapture);
    input = sentenceRegex.Replace(input.ToLower(), s => s.Value.ToUpper());
    
    0 讨论(0)
提交回复
热议问题