如何转换字符串,使每个单词的第一个字符大写,其余字符小写?

时间:2019-02-24 16:05:13

标签: c#

到目前为止,我有这段代码将每个字符都转换为大写:

    public string Header
    {
        get
        {
            var value = (string)GetValue(HeaderProperty);
            return !string.IsNullOrEmpty(value) ? value.ToUpper() : value;
        }
        set
        {
            SetValue(HeaderProperty, value);
        }
    }

但是我只想转换每个单词的第一个字符。有什么功能可以让我做到这一点?

5 个答案:

答案 0 :(得分:5)

您可以像下面这样使用ToTitleCase

return System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(value.ToLower());

答案 1 :(得分:0)

您本质上是想要这样做的(您可以在外部函数中甚至是内联函数中实现。
(外部功能)

Function myResult(NamedRange As Range, Vessel As String, FromDate As Date, ToDate As Date)

'declare variables in addition to the function parameters declared above
Dim SpecificRange As Range
Dim FullRange As Range
Dim Result As Double
Dim i As Byte

'find the row within the declared "NamedRange" range which contains information for the declared "Vessel"
Set FullRange = NamedRange
Set SpecificRange = Range(FullRange.Find(Vessel, , xlValues, xlWhole).Address, FullRange.Find(Vessel, , xlValues, xlWhole).Offset(0, FullRange.Columns.Count - 1).Address)

i = 1
Result = 0

For i = 1 To FullRange.Columns.Count - 2
    If FullRange(2, i) = "Date" Then
        With WorksheetFunction
            Result = Result + .Max(0, .Min(ToDate, SpecificRange(1, i + 2).Value) - .Max(FromDate, SpecificRange(1, i).Value)) * SpecificRange(1, i + 1).Value
        End With
    End If
Next

myResult = Result

End Function

或内联:

public static string FistCharacterToUpper(string input)
    {
        string temp = input.First().ToString().ToUpper() + input.Substring(1);
        return temp;
    }

答案 2 :(得分:0)

尝试

q)2+5?9
10 2 7 10 7

答案 3 :(得分:0)

您可以使用chars来解决此问题:))

static string Conv(string inp)
{
   inp = inp[0].ToString().ToUpper() + inp.Substring(1, inp.Length - 1).ToLower();
   return inp;
}

答案 4 :(得分:0)

我正在构建一个可以添加到任何项目的全局“实用程序”类。在其中有许多有用的功能,我还在其中添加了扩展方法。想一想,也许将其作为扩展方法可能会有用。

public static string ToTitleCase(this string inString) => new CultureInfo("en-US", false).TextInfo.ToTitleCase(inString);

用法:

string test = "wAr aNd pEaCe";

test = test.ToTitleCase();