[英]How to capitalize the first character of each word, or the first character of a whole string, with C#?
我可以编写自己的算法来做到这一点,但我觉得在 C# 中应该有相当于ruby 的人性化。
我用谷歌搜索,但只找到了人性化日期的方法。
例子:
正如@miguel 的回答的评论中所讨论的,您可以使用自 .NET 1.1 起可用的TextInfo.ToTitleCase
。 以下是与您的示例相对应的一些代码:
string lipsum1 = "Lorem lipsum et";
// Creates a TextInfo based on the "en-US" culture.
TextInfo textInfo = new CultureInfo("en-US",false).TextInfo;
// Changes a string to titlecase.
Console.WriteLine("\"{0}\" to titlecase: {1}",
lipsum1,
textInfo.ToTitleCase( lipsum1 ));
// Will output: "Lorem lipsum et" to titlecase: Lorem Lipsum Et
它将忽略所有大写的大小写,例如“LOREM LIPSUM ET”,因为它会处理文本中的首字母缩略词,以便“IEEE”(电气和电子工程师协会)不会成为“ieee”或“伊”。
但是,如果您只想大写第一个字符,您可以执行此处的解决方案……或者您可以拆分字符串并大写列表中的第一个字符:
string lipsum2 = "Lorem Lipsum Et";
string lipsum2lower = textInfo.ToLower(lipsum2);
string[] lipsum2split = lipsum2lower.Split(' ');
bool first = true;
foreach (string s in lipsum2split)
{
if (first)
{
Console.Write("{0} ", textInfo.ToTitleCase(s));
first = false;
}
else
{
Console.Write("{0} ", s);
}
}
// Will output: Lorem lipsum et
使用正则表达式看起来更干净:
string s = "the quick brown fox jumps over the lazy dog";
s = Regex.Replace(s, @"(^\w)|(\s\w)", m => m.Value.ToUpper());
还有另一个优雅的解决方案:
在项目的静态类中定义函数ToTitleCase
using System.Globalization;
public static string ToTitleCase(this string title)
{
return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(title.ToLower());
}
然后在项目的任何地方使用它作为字符串扩展:
"have a good day !".ToTitleCase() // "Have A Good Day !"
所有的例子似乎首先降低了其他字符,这不是我需要的。
customerName
= CustomerName
<-- 这就是我想要的
this is an example
= This Is An Example
public static string ToUpperEveryWord(this string s)
{
// Check for empty string.
if (string.IsNullOrEmpty(s))
{
return string.Empty;
}
var words = s.Split(' ');
var t = "";
foreach (var word in words)
{
t += char.ToUpper(word[0]) + word.Substring(1) + ' ';
}
return t.Trim();
}
如果您只想将第一个字符大写,只需将其粘贴到您自己的实用方法中即可:
return string.IsNullOrEmpty(str)
? str
: str[0].ToUpperInvariant() + str.Substring(1).ToLowerInvariant();
还有一个库方法可以将每个单词的第一个字符大写:
http://msdn.microsoft.com/en-us/library/system.globalization.textinfo.totitlecase.aspx
CSS 技术还可以,但只会改变字符串在浏览器中的呈现方式。 更好的方法是在发送到浏览器之前使文本本身大写。
上面的大多数实现都可以,但它们都没有解决如果您有需要保留的混合大小写单词,或者如果您想使用真正的标题案例会发生什么的问题,例如:
“在美国哪里学习博士课程”
要么
“国税局表格 UB40a”
同样使用 CultureInfo.CurrentCulture.TextInfo.ToTitleCase(string) 会保留大写单词,如“sports and MLB 棒球”中的“体育和 MLB 棒球”,但如果整个字符串都为大写,则会导致问题。
所以我组合了一个简单的函数,通过将它们包含在 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 服务中具有首字母缩略词和大写/小写单词的查找表,以便可以从一个位置维护混合大小写单词列表并应用于许多不同的依赖于该功能的应用程序。
我使用自定义扩展方法实现了相同的目标。 对于第一个子字符串的首字母,请使用yourString.ToFirstLetterUpper()
方法。 对于不包括文章和一些命题的每个子字符串的首字母,请使用yourString.ToAllFirstLetterInUpper()
方法。 下面是一个控制台程序:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("this is my string".ToAllFirstLetterInUpper());
Console.WriteLine("uniVersity of lonDon".ToAllFirstLetterInUpper());
}
}
public static class StringExtension
{
public static string ToAllFirstLetterInUpper(this string str)
{
var array = str.Split(" ");
for (int i = 0; i < array.Length; i++)
{
if (array[i] == "" || array[i] == " " || listOfArticles_Prepositions().Contains(array[i])) continue;
array[i] = array[i].ToFirstLetterUpper();
}
return string.Join(" ", array);
}
private static string ToFirstLetterUpper(this string str)
{
return str?.First().ToString().ToUpper() + str?.Substring(1).ToLower();
}
private static string[] listOfArticles_Prepositions()
{
return new[]
{
"in","on","to","of","and","or","for","a","an","is"
};
}
}
输出
This is My String
University of London
Process finished with exit code 0.
.NET 中没有用于正确语言大写的预构建解决方案。 你想要什么样的大写? 您是否遵循《芝加哥风格手册》惯例? AMA 还是 MLA? 即使是简单的英语句子大写也有 1000 多个单词的特殊例外。 我无法谈论 ruby 的 humanize 做了什么,但我想它可能不遵循大写的语言规则,而是做一些更简单的事情。
在内部,我们遇到了同样的问题,不得不编写相当多的代码来处理适当的(在我们的小世界中)文章标题的大小写,甚至不考虑句子大写。 它确实变得“模糊”:)
这真的取决于你需要什么——你为什么要尝试将句子转换为正确的大写(以及在什么上下文中)?
据我所知,没有编写(或抄袭)代码就没有办法做到这一点。 C# nets (ha!) 你的上限、下限和标题(你拥有的)案例:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.