[点晴永久免费OA]C#中字符串的大小写多种转换需求实现
|
admin
2024年10月18日 9:5
本文热度 881
|
前言
在 .NET 中,字符串是一个非常重要的数据类型。由于英文字母存在大小写的区别,所以 C# 的 String类提供了ToUpper 与 ToLower 方法,它们分别可将字符串的字符转换为大写或小写。本文将探索或回顾C#实现字符串的大小写转换。
示例
1、将字符串转换为大写和小写字符串
namespace Fountain.WinConsole.StriingDemo
{
internal class Program
{
static void Main(string[] args)
{
string author = "Fountyuan";
string title = "Fountyuan is a Author of WeiXin official Account article.";
// 将所有内容转换为大写
string ucaseAuthor = author.ToUpper();
Console.WriteLine($"大写: {ucaseAuthor}");
// 将所有内容转换为小写
string lcaseAuthor = author.ToLower();
Console.WriteLine($"小写: {lcaseAuthor}");
// 我们可以直接转换为大写或小写
Console.WriteLine(title.ToLower());
Console.WriteLine(title.ToUpper());
Console.ReadKey();
}
}
}

2、将字符串的首字母转换为大写
namespace Fountain.WinConsole.StriingDemo
{
internal class Program
{
static void Main(string[] args)
{
// 将字符串的首字母转换为大写
string temp = "in an Excel file.";
if (!string.IsNullOrEmpty(temp))
{
temp = string.Format("{0}{1}",char.ToUpper(temp[0]),temp.Substring(1));
}
Console.WriteLine($"首字母大写的字符串:{temp}");
Console.ReadKey();
}
}
}

3、将字符串某部分转换为小写或大写
namespace Fountain.WinConsole.StriingDemo
{
internal class Program
{
static void Main(string[] args)
{
// 将字符串某部分转换为小写或大写
string fileType = "EXCEL FILE";
string updatedType = fileType.Substring(0, 1).ToUpper() + fileType.Substring(1).ToLower();
Console.WriteLine(updatedType);
Console.ReadKey();
}
}
}

4、将字符串中每个单词的首字符大写
using System.Globalization;
namespace Fountain.WinConsole.StriingDemo
{
internal class Program
{
static void Main(string[] args)
{
// 将字符串中每个单词的首字符大写
string content = "fountyuan is a author of weixin official account article.";
string updateContent = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(content);
Console.WriteLine(updateContent);
Console.ReadKey();
}
}
}

小结
.NET 提供的 ToUpper 和 ToLower 方法很容易使用,以上通过示例重温字符串的大小写转换,如有不到之处,请多多包涵。
该文章在 2024/10/19 16:23:18 编辑过