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
Python String title() Method The title() method returns a string where the first character in every word is upper case. Like a header, or a title. If the word contains a number or a symbol, the first letter after that will be converted to upper case.
split() method. Convert all the elements in each and every word in to lowercase using string. toLowerCase() method. Loop through first elements of all the words using for loop and convert them in to uppercase.
In title case, capitalize the following words in a title or heading: the first word of the title or heading, even if it is a minor word such as “The” or “A” the first word of a subtitle. the first word after a colon, em dash, or end punctuation in a heading.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With