c# 正则表达式 首字母转大写

本文介绍了一个C#中的实用工具方法,该方法能够将输入字符串中每个单词的首字母转换为大写。通过使用正则表达式和委托函数,此方法提供了灵活且高效的字符串操作方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 1     class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5             // Input strings.
 6             const string s1 = "samuel allen";
 7             const string s2 = "dot net perls";
 8             const string s3 = "Uppercase first letters of all words in the string.";
 9 
10             // Write output strings.
11             Console.WriteLine(TextTools.UpperFirst(s1));
12             Console.WriteLine(TextTools.UpperFirst(s2));
13             Console.WriteLine(TextTools.UpperFirst(s3));
14             Console.ReadKey();
15         }
16     }
17 
18     public static class TextTools
19     {
20         /// <summary>
21         /// Uppercase first letters of all words in the string.
22         /// </summary>
23         public static string UpperFirst(string s)
24         {
25             return Regex.Replace(s, @"\b[a-z]\w+", delegate(Match match)
26             {
27                 string v = match.ToString();
28                 return char.ToUpper(v[0]) + v.Substring(1);
29             });
30         }
31     }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值