Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
546 views
in Technique[技术] by (71.8m points)

c# - Transform string to title case

I need to convert to title case the following:

  1. First word in a phrase;

  2. Other words, in the same phrase, which length is greater than minLength.

I was looking at ToTitleCase but the result is not the expected.

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, @"(w|['-])+"

But I am not sure how to put all this together

Thank You, Miguel

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Sample code:

string input = "i have the car which is very fast";
int minLength = 2;
string regexPattern = string.Format(@"^w|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|w(?=w{{{0}}})", minLength);
string output = Regex.Replace(input, regexPattern, m => m.Value.ToUpperInvariant());

Output:

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|w(?=w{{{0}}})", minLength);
string output = Regex.Replace(input, regexPattern, m => m.Value.ToUpperInvariant());

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|w(?=[-w]{{{0}}})", minLength);
string output = Regex.Replace(input, regexPattern, m => m.Value.ToUpperInvariant());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...