我有一个字符串,其中包含大小写混合的单词。

例如:string myData = "一个简单字符串";

我需要将每个单词的第一个字符(由空格分隔)转换为大写。所以我想要的结果为:字符串myData ="一个简单的字符串";

有什么简单的方法吗?我不想分割字符串并进行转换(这将是我最后的手段)。另外,它保证字符串是英文的。


当前回答

这是另一种变化。基于这里的几个技巧,我将其简化为以下扩展方法,它非常适合我的目的:

public static string ToTitleCase(this string s) =>
    CultureInfo.InvariantCulture.TextInfo.ToTitleCase(s.ToLower());

其他回答

作为扩展方法:

/// <summary>
//     Returns a copy of this string converted to `Title Case`.
/// </summary>
/// <param name="value">The string to convert.</param>
/// <returns>The `Title Case` equivalent of the current string.</returns>
public static string ToTitleCase(this string value)
{
    string result = string.Empty;

    for (int i = 0; i < value.Length; i++)
    {
        char p = i == 0 ? char.MinValue : value[i - 1];
        char c = value[i];

        result += char.IsLetter(c) && ((p is ' ') || p is char.MinValue) ? $"{char.ToUpper(c)}" : $"{char.ToLower(c)}";
    }

    return result;
}

用法:

"kebab is DELICIOU's   ;d  c...".ToTitleCase();

结果:

Kebab Is Deliciou's;d C…

public static string PropCase(string strText)
{
    return new CultureInfo("en").TextInfo.ToTitleCase(strText.ToLower());
}

在检查null或空字符串值以消除错误后,您可以直接使用这个简单的方法将文本或字符串更改为正确的:

// Text to proper (Title Case):
    public string TextToProper(string text)
    {
        string ProperText = string.Empty;
        if (!string.IsNullOrEmpty(text))
        {
            ProperText = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(text);
        }
        else
        {
            ProperText = string.Empty;
        }
        return ProperText;
    }

首先使用ToLower(),然后对结果使用CultureInfo.CurrentCulture.TextInfo.ToTitleCase以获得正确的输出。

    //---------------------------------------------------------------
    // Get title case of a string (every word with leading upper case,
    //                             the rest is lower case)
    //    i.e: ABCD EFG -> Abcd Efg,
    //         john doe -> John Doe,
    //         miXEd CaSING - > Mixed Casing
    //---------------------------------------------------------------
    public static string ToTitleCase(string str)
    {
        return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str.ToLower());
    }
String TitleCaseString(String s)
{
    if (s == null || s.Length == 0) return s;

    string[] splits = s.Split(' ');

    for (int i = 0; i < splits.Length; i++)
    {
        switch (splits[i].Length)
        {
            case 1:
                break;

            default:
                splits[i] = Char.ToUpper(splits[i][0]) + splits[i].Substring(1);
                break;
        }
    }

    return String.Join(" ", splits);
}