代码之家  ›  专栏  ›  技术社区  ›  juan

有大写字母的方法吗?

  •  7
  • juan  · 技术社区  · 17 年前

    有没有办法做到这一点?可以用扩展方法来完成吗?

    我想做到这一点:

    string s = "foo".CapitalizeFirstLetter();
    // s is now "Foo"
    
    3 回复  |  直到 17 年前
        1
  •  19
  •   Community Mohan Dere    9 年前

    一个简单的扩展方法,将字符串的第一个字母大写。正如Karl指出的,这假设第一个字母是正确的,因此不是完全安全的。

    public static string CapitalizeFirstLetter(this String input)
    {
        if (string.IsNullOrEmpty(input)) 
            return input;
    
        return input.Substring(0, 1).ToUpper(CultureInfo.CurrentCulture) +
            input.Substring(1, input.Length - 1);
    }
    

    你也可以使用 System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase . 该函数将转换的第一个字符 每一个字 大写。所以如果你的输入字符串是 have fun Have Fun .

    public static string CapitalizeFirstLetter(this String input)
    {
         if (string.IsNullOrEmpty(input)) 
             return input;
    
         return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(input);
    }
    

    看见 this question 了解更多信息。

        2
  •  10
  •   Chris    17 年前
        3
  •  0
  •   JoelFan    13 年前

    static public string UpperCaseFirstCharacter(this string text) {
        return Regex.Replace(text, "^[a-z]", m => m.Value.ToUpper());
    }
    
    推荐文章