更改大小写

更新:2007 年 11 月

如果编写接受用户输入的应用程序,您可能无法确定他或她是使用大写还是小写来输入数据。因为比较字符串和字符的方法是区分大小写的,所以在将用户输入的字符串与常数值进行比较之前,应转换这些字符串的大小写。可以很容易更改字符串的大小写。下表描述了两个更改大小写的方法。每个方法都提供一个接受区域性的重载。

方法名

用途

String.ToUpper

将字符串中的所有字符转换为大写。

String.ToLower

将字符串中的所有字符转换为小写。

ToUpper

String.ToUpper 方法将字符串中的所有字符更改为大写。下面的示例将字符串“Hello World!”从混合大小写更改为全部大写。

Dim MyString As String = "Hello World!"
Console.WriteLine(MyString.ToUpper())
' This example displays the following output:
'       HELLO WORLD!
string properString = "Hello World!";
Console.WriteLine(properString.ToUpper());
// This example displays the following output:
//       HELLO WORLD!

上面的示例默认情况下区分区域性,它应用当前区域性的大小写约定。若要执行不区分区域性的大小写更改,或应用特定区域性的大小写约定,请使用 String.ToUpper(CultureInfo) 方法重载,并将值 CultureInfo.InvariantCulture 或表示指定区域性的 System.Globalization.CultureInfo 对象传给 culture 参数。若要查看演示如何用 ToUpper 方法执行不区分区域性的大小写更改的示例,请参见执行不区分区域性的大小写更改

ToLower

String.ToLower 方法类似于前面的方法,但不同的是它将字符串中的所有字符转换为小写。下面的示例将字符串“Hello World!”转换为小写。

Dim MyString As String = "Hello World!"
Console.WriteLine(MyString.ToLower())
' This example displays the following output:
'       hello world!
string properString = "Hello World!";
Console.WriteLine(properString.ToLower());
// This example displays the following output:
//       hello world!

上面的示例默认情况下区分区域性,它应用当前区域性的大小写约定。若要执行不区分区域性的大小写转换,或应用特定区域性的大小写约定,请使用 String.ToLower(CultureInfo) 方法重载,并将值 CultureInfo.InvariantCulture 或表示指定区域性的 System.Globalization.CultureInfo 对象传给 culture 参数。若要查看演示如何用 ToLower(CultureInfo) 方法执行不区分区域性的大小写更改的示例,请参见执行不区分区域性的大小写更改

请参见

其他资源

基本字符串操作

执行不区分区域性的字符串操作