Transform string to title case
c#
Solution
Sample code:
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());
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|\b\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|\b\w(?=[-\w]{{{0}}})", minLength);
string output = Regex.Replace(input, regexPattern, m => m.Value.ToUpperInvariant());
Problem
I need to convert to title case the following: First word in a phrase; 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, @"\b(\w|['-])+\b" ``` But I am not sure how to put all this together Thank You, Miguel