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

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

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

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


当前回答

最好通过尝试自己的代码来理解…

阅读更多

http://www.stupidcodes.com/2014/04/convert-string-to-uppercase-proper-case.html

1)将字符串转换为大写

string lower = "converted from lowercase";
Console.WriteLine(lower.ToUpper());

2)将字符串转换为小写

string upper = "CONVERTED FROM UPPERCASE";
Console.WriteLine(upper.ToLower());

3)转换String为TitleCase

    CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
    TextInfo textInfo = cultureInfo.TextInfo;
    string txt = textInfo.ToTitleCase(TextBox1.Text());

其他回答

就我个人而言,我尝试了TextInfo。ToTitleCase方法,但是,我不明白为什么当所有字符都是大写的时候它不起作用。

虽然我喜欢Winston Smith提供的util函数,但让我提供我目前正在使用的函数:

public static String TitleCaseString(String s)
{
    if (s == null) return s;

    String[] words = s.Split(' ');
    for (int i = 0; i < words.Length; i++)
    {
        if (words[i].Length == 0) continue;

        Char firstChar = Char.ToUpper(words[i][0]); 
        String rest = "";
        if (words[i].Length > 1)
        {
            rest = words[i].Substring(1).ToLower();
        }
        words[i] = firstChar + rest;
    }
    return String.Join(" ", words);
}

玩一些测试字符串:

String ts1 = "Converting string to title case in C#";
String ts2 = "C";
String ts3 = "";
String ts4 = "   ";
String ts5 = null;

Console.Out.WriteLine(String.Format("|{0}|", TitleCaseString(ts1)));
Console.Out.WriteLine(String.Format("|{0}|", TitleCaseString(ts2)));
Console.Out.WriteLine(String.Format("|{0}|", TitleCaseString(ts3)));
Console.Out.WriteLine(String.Format("|{0}|", TitleCaseString(ts4)));
Console.Out.WriteLine(String.Format("|{0}|", TitleCaseString(ts5)));

给输出:

|Converting String To Title Case In C#|
|C|
||
|   |
||

在检查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;
    }

对于那些想要自动按下键盘的人,我用下面的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

试试这个:

string myText = "a Simple string";

string asTitleCase =
    System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.
    ToTitleCase(myText.ToLower());

如前所述,使用TextInfo。ToTitleCase可能不会给您想要的确切结果。如果你需要更多的输出控制,你可以这样做:

IEnumerable<char> CharsToTitleCase(string s)
{
    bool newWord = true;
    foreach(char c in s)
    {
        if(newWord) { yield return Char.ToUpper(c); newWord = false; }
        else yield return Char.ToLower(c);
        if(c==' ') newWord = true;
    }
}

然后像这样使用它:

var asTitleCase = new string( CharsToTitleCase(myText).ToArray() );

不使用TextInfo:

public static string TitleCase(this string text, char seperator = ' ') =>
  string.Join(seperator, text.Split(seperator).Select(word => new string(
    word.Select((letter, i) => i == 0 ? char.ToUpper(letter) : char.ToLower(letter)).ToArray())));

它循环每个单词中的每个字母,如果它是第一个字母,则将其转换为大写字母,否则将其转换为小写字母。