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

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

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

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


当前回答

首先使用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());
    }

其他回答

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

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

最近我找到了一个更好的解决方案。

如果文本中每个字母都是大写的,那么TextInfo将不会将其转换为正确的大小写。我们可以通过使用里面的小写函数来解决这个问题,就像这样:

public static string ConvertTo_ProperCase(string text)
{
    TextInfo myTI = new CultureInfo("en-US", false).TextInfo;
    return myTI.ToTitleCase(text.ToLower());
}

现在这将把所有输入的内容转换为Propercase。

下面是这个问题的解决方案……

CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
TextInfo textInfo = cultureInfo.TextInfo;
string txt = textInfo.ToTitleCase(txt);
public static string PropCase(string strText)
{
    return new CultureInfo("en").TextInfo.ToTitleCase(strText.ToLower());
}

对于那些想要自动按下键盘的人,我用下面的VB代码做到了。NET在一个自定义文本框控件上-你显然也可以用一个普通的文本框来做-但是我喜欢通过自定义控件为特定控件添加循环代码的可能性,它适合OOP的概念。

Imports System.Windows.Forms
Imports System.Drawing
Imports System.ComponentModel

Public Class MyTextBox
    Inherits System.Windows.Forms.TextBox
    Private LastKeyIsNotAlpha As Boolean = True
    Protected Overrides Sub OnKeyPress(e As KeyPressEventArgs)
        If _ProperCasing Then
            Dim c As Char = e.KeyChar
            If Char.IsLetter(c) Then
                If LastKeyIsNotAlpha Then
                    e.KeyChar = Char.ToUpper(c)
                    LastKeyIsNotAlpha = False
                End If
            Else
                LastKeyIsNotAlpha = True
            End If
        End If
        MyBase.OnKeyPress(e)
End Sub
    Private _ProperCasing As Boolean = False
    <Category("Behavior"), Description("When Enabled ensures for automatic proper casing of string"), Browsable(True)>
    Public Property ProperCasing As Boolean
        Get
            Return _ProperCasing
        End Get
        Set(value As Boolean)
            _ProperCasing = value
        End Set
    End Property
End Class