2013-02-04 20 views
1

在最近的一個項目上工作時一直在困擾着我;爲什麼C#沒有本地函數來將字符串更改爲標題大小寫?爲什麼沒有本地字符串方法來更改字符串標題大小寫?

例如

string x = "hello world! THiS IS a Test mESSAGE"; 
string y = x.ToTitle(); // y now has value of "Hello World! This Is A Test Message" 

我們有.ToLower.ToUpper,我很欣賞你可以使用System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase或創建TextInfo對象(同樣的過程),但它只是如此...難看。

有人知道原因嗎?

+3

什麼是醜* *? –

+2

它是CultureInfo的一部分,因爲它因文化而異。 –

+1

但ToUpper/ToLower也因文化而異(或應該這樣做)。 – Rawling

回答

1

其實它具有:TextInfo.ToTitleCase

爲什麼它的存在?因爲套管取決於當前的文化。例如。對於'我'和'我'字符,土耳其文化有不同的大寫和小寫。閱讀更多關於這個here

更新:其實我同意@Cashley,它說,缺少ToTitleCase方法String類看起來像一個MicroSoft的疏忽。如果你會看在String.ToUpper()String.ToLower()你會看到,無論使用TextInfo內部:

public string ToUpper() 
{ 
    return this.ToUpper(CultureInfo.CurrentCulture); 
} 

public string ToUpper(CultureInfo culture) 
{ 
    if (culture == null)  
     throw new ArgumentNullException("culture"); 

    return culture.TextInfo.ToUpper(this); 
} 

所以,我覺得應該有相同的方法ToTitleCase()。也許.NET團隊決定增加String類只有那些主要使用的方法。我沒有看到其他任何保持ToTitleCase的理由。

+1

那麼爲什麼不把ToUpper和ToLower降級到'TextInfo',因爲它們有相同的文化問題? – Rawling

+0

看起來像[String在內部使用CultureInfo](http://reflector.webtropy.com/default.aspx/[email protected]/[email protected]/DEVDIV_TFS/Dev10/Releases/RTMRel/ndp/clr/src/BCL/System/字符串@ cs/1305376 /字符串@ cs) - 我想只是MS的一部分沒有添加ToTitleCase到字符串的監督。 – Cashley

+0

解釋它!我會把它寫成微軟的疏忽,但如果他們解決了它,它會很好... – loxdog

0

There's an extension method在這裏,但它不是文化特定的。

可能更好的實現只是包裝CurrentCulture.TextInfo像String.ToUpper:

class Program 
{ 
    static void Main(string[] args) 
    { 
     string s = "test Title cAsE"; 
     s = s.ToTitleCase(); 
     Console.Write(s); 
    } 
} 
public static class StringExtensions 
{ 
    public static string ToTitleCase(this string inputString) 
    { 
     return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(inputString); 
    } 

    public static string ToTitleCase(this string inputString, CultureInfo ci) 
    { 
     return ci.TextInfo.ToTitleCase(inputString); 
    } 
} 
0
Dim myString As String = "wAr aNd pEaCe" 

    ' Creates a TextInfo based on the "en-US" culture. 
    Dim myTI As TextInfo = New CultureInfo("en-US", False).TextInfo 

    ' Changes a string to titlecase. 
    Console.WriteLine("""{0}"" to titlecase: {1}", myString, myTI.ToTitleCase(myString)) 

OR

string myString = "wAr aNd pEaCe"; 

    // Creates a TextInfo based on the "en-US" culture. 
    TextInfo myTI = new CultureInfo("en-US", false).TextInfo; 

    // Changes a string to titlecase. 
    Console.WriteLine("\"{0}\" to titlecase: {1}", myString, myTI.ToTitleCase(myString)); 
相關問題