将字符串转换为标题大小写 [英] Transform string to title case
问题描述
我需要将以下内容转换为标题:
I need to convert to title case the following:
-
短语中的第一个单词;
First word in a phrase;
在同一短语中的其他单词,其长度大于minLength.
Other words, in the same phrase, which length is greater than minLength.
我正在查看 ToTitleCase ,但是结果不是预期的.
I was looking at ToTitleCase but the result is not the expected.
因此,minLength = 2的短语汽车非常快"将变为汽车非常快"快速".
So the phrase "the car is very fast" with minLength = 2 would become "The Car is Very Fast".
我能够使用以下命令将第一个单词大写:
I was able to make the first word uppercase using:
Char[] letters = source.ToCharArray();
letters[0] = Char.ToUpper(letters[0]);
并得到我正在使用的单词:
And to get the words I was using:
Regex.Matches(source, @"\b(\w|['-])+\b"
但是我不确定如何将所有这些放在一起
But I am not sure how to put all this together
谢谢,米格尔(Miguel)
Thank You, Miguel
推荐答案
示例代码:
string input = "i have the car which is very fast";
int minLength = 2;
string regexPattern = string.Format(@"^\w|\b\w(?=\w{{{0}}})", minLength);
string output = Regex.Replace(input, regexPattern, m => m.Value.ToUpperInvariant());
更新(对于单个字符串中包含多个句子的情况).
UPDATE (for the cases where you have multiple sentences in single string).
string input = "i have the car which is very fast. me is slow.";
int minLength = 2;
string regexPattern = string.Format(@"(?<=(^|\.)\s*)\w|\b\w(?=\w{{{0}}})", minLength);
string output = Regex.Replace(input, regexPattern, m => m.Value.ToUpperInvariant());
输出:
I Have The Car Which is Very Fast. Me is Slow.
您可能希望处理!
,?
和其他符号,然后可以使用以下符号.您可以根据需要添加任意数量的句子终止符号.
You may wish to handle !
, ?
and other symbols, then you can use the following. You can add as many sentence terminating symbols as you wish.
string input = "i have the car which is very fast! me is slow.";
int minLength = 2;
string regexPattern = string.Format(@"(?<=(^|[.!?])\s*)\w|\b\w(?=\w{{{0}}})", minLength);
string output = Regex.Replace(input, regexPattern, m => m.Value.ToUpperInvariant());
更新(2)-将 e-marketing
转换为 E-marketing
(将-
视为有效词)符号):
UPDATE (2) - convert e-marketing
to E-Marketing
(consider -
as valid word symbol):
string input = "i have the car which is very fast! me is slow. it is very nice to learn e-marketing these days.";
int minLength = 2;
string regexPattern = string.Format(@"(?<=(^|[.!?])\s*)\w|\b\w(?=[-\w]{{{0}}})", minLength);
string output = Regex.Replace(input, regexPattern, m => m.Value.ToUpperInvariant());
这篇关于将字符串转换为标题大小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!