CSS 技术没问题,但只会改变字符串在浏览器中的呈现方式。更好的方法是在发送到浏览器之前使文本本身大写。
上面的大多数实现都是可以的,但是它们都没有解决如果你有混合大小写的单词需要保留,或者如果你想使用真正的标题大小写会发生什么的问题,例如:
“去美国读博士课程的地方”
或
“IRS 表格 UB40a”
还使用 CultureInfo.CurrentCulture.TextInfo.ToTitleCase(string) 保留大写单词,如
“sports and MLB棒球”变成了“Sports And MLB Baseball”,但如果整个字符串都是大写的,那么这会导致问题。
所以我整理了一个简单的函数,通过将它们包含在 specialCases 和 lowerCases 字符串中,您可以保留大写单词和混合大小写单词,并使小单词小写(如果它们不在短语的开头和结尾)数组:
public static string TitleCase(string value) {
string titleString = ""; // destination string, this will be returned by function
if (!String.IsNullOrEmpty(value)) {
string[] lowerCases = new string[12] { "of", "the", "in", "a", "an", "to", "and", "at", "from", "by", "on", "or"}; // list of lower case words that should only be capitalised at start and end of title
string[] specialCases = new string[7] { "UK", "USA", "IRS", "UCLA", "PHd", "UB40a", "MSc" }; // list of words that need capitalisation preserved at any point in title
string[] words = value.ToLower().Split(' ');
bool wordAdded = false; // flag to confirm whether this word appears in special case list
int counter = 1;
foreach (string s in words) {
// check if word appears in lower case list
foreach (string lcWord in lowerCases) {
if (s.ToLower() == lcWord) {
// if lower case word is the first or last word of the title then it still needs capital so skip this bit.
if (counter == 0 || counter == words.Length) { break; };
titleString += lcWord;
wordAdded = true;
break;
}
}
// check if word appears in special case list
foreach (string scWord in specialCases) {
if (s.ToUpper() == scWord.ToUpper()) {
titleString += scWord;
wordAdded = true;
break;
}
}
if (!wordAdded) { // word does not appear in special cases or lower cases, so capitalise first letter and add to destination string
titleString += char.ToUpper(s[0]) + s.Substring(1).ToLower();
}
wordAdded = false;
if (counter < words.Length) {
titleString += " "; //dont forget to add spaces back in again!
}
counter++;
}
}
return titleString;
}
这只是一种快速简单的方法 - 如果您想花更多时间在上面,可能会有所改进。
如果您想保留“a”和“of”等较小单词的大写,则只需将它们从特殊情况字符串数组中删除即可。不同的组织对大小写有不同的规定。
您可以在此站点上看到此代码的示例:Egg Donation London - 此站点通过解析 URL 自动在页面顶部创建面包屑路径,例如“/services/uk-egg-bank/introduction” - 然后路径中的每个文件夹名称都将连字符替换为空格并将文件夹名称大写,因此 uk-egg-bank 变为 UK Egg Bank。 (保留大写“UK”)
此代码的扩展可能是在共享文本文件、数据库表或 Web 服务中具有首字母缩略词和大写/小写单词的查找表,以便可以从一个位置维护混合大小写单词列表并应用到许多依赖该函数的不同应用程序。