C#如何按英文规则将字符串转为标题大小写(小写连词)
实现符合英文规则的标题大小写转换(C#)
嘿,这个问题我之前帮不少开发者解决过——.NET自带的ToTitleCase()确实有点“死板”,会把所有单词的首字母都大写,完全不符合英文标题里小词(比如of、the这类介词/连词)小写的规则。下面给你两个实用的解决方案,完美搞定这个需求:
方案一:自定义排除词+手动处理逻辑
先定义好需要保留小写的小词列表,先通过ToTitleCase()把所有单词转成首字母大写,再把中间位置的小词转回小写(注意标题首尾的小词还是要大写的,这是英文标题的规则)。
代码示例:
using System; using System.Globalization; using System.Linq; class Program { static void Main() { string title = "the lord of the rings"; TextInfo textInfo = new CultureInfo("en-US", false).TextInfo; // 先转成默认的标题大小写格式 string tempTitle = textInfo.ToTitleCase(title.ToLower()); // 定义需要小写的小词列表,可根据规则扩展 var lowercaseWords = new[] { "of", "the", "and", "or", "nor", "but", "a", "an", "in", "on", "at", "to", "for" }; // 拆分单词并处理中间的小词 var words = tempTitle.Split(' '); for (int i = 1; i < words.Length - 1; i++) { if (lowercaseWords.Contains(words[i].ToLower())) { words[i] = words[i].ToLower(); } } string finalTitle = string.Join(" ", words); Console.WriteLine(finalTitle); // 输出:The Lord of the Rings } }
方案二:正则表达式快速替换
用正则匹配标题中间的小词,直接替换为小写,这种方式代码更简洁,适合快速实现:
using System; using System.Globalization; using System.Text.RegularExpressions; class Program { static void Main() { string title = "the lord of the rings"; TextInfo textInfo = new CultureInfo("en-US", false).TextInfo; string tempTitle = textInfo.ToTitleCase(title.ToLower()); // 正则匹配不在首尾的小词,替换为小写 string finalTitle = Regex.Replace(tempTitle, @"\b(of|the|and|or|nor|but|a|an|in|on|at|to|for)\b", match => match.Value.ToLower(), RegexOptions.IgnoreCase); // 保险起见,确保标题首字母大写(避免极端情况) finalTitle = char.ToUpper(finalTitle[0]) + finalTitle.Substring(1); Console.WriteLine(finalTitle); // 输出:The Lord of the Rings } }
额外提醒
- 你可以根据英文标题的具体规则,扩展小词列表,比如加上
with、by这类介词; - 如果标题里有专有名词、缩写,可能需要额外逻辑保留它们的大小写;要是标题包含冒号、破折号,冒号/破折号后的第一个单词首字母也要大写,这时候可以调整正则或者处理逻辑;
- 如果要适配英式英语,只需要把
CultureInfo("en-US")改成CultureInfo("en-GB")就行,规则基本一致。
内容的提问来源于stack exchange,提问作者Matt McManis
相关产品推荐
相关产品推荐

