I wonder why this is not in the answer list: Here is the one liner
string input = "this string will be converted into title case";
var titleCase = string.Join(" ", input.Split(' ').Select(i => $"{i.Remove(1).ToUpper()}{i.Substring(1).ToLower()}"));
titleCase.Dump();
Console.WriteLine(titleCase);
this is without any dependency even without using System.Globalization
.
Note: If you change the Remove(1)
& Substring(1)
character from 1 to 2 it will make first two character capital and so on
How it works ?
- The
input.Remove(1)
extracts the first character which is t
in the example above and converts it in upper case using ToUpper()
which makes T
input.Substring(1)
removes the first character from the input
in example
- The result from 1 & 2 are concerted with
$"{} {}"
to form the result
How to use
This can be crafted as Func as
Func<string,string> TitleCase = (ins) =>{
return string.Join(" ", ins.Split(' ').Select(i => $"{i.Remove(1).ToUpper()}{i.Substring(1).ToLower()}"));
};
Console.WriteLine(TitleCase(input));
Or as an Extension function
public static class StringExt
{
public static string ToTitleCase(this string input)
{
return string.Join(" ", input.Split(' ').Select(i => $"{i.Remove(1).ToUpper()}{i.Substring(1).ToLower()}"));
}
}
Console.WriteLine(input.ToTitleCase());