I have a string that I converted to a TextInfo.ToTitleCase and removed the underscores and joined the string together. Now I need to change the first and only the first character in the string to lower case and for some reason, I can not figure out how to accomplish it. Thanks in advance for the help.
class Program { static void Main(string[] args) { string functionName = "zebulans_nightmare"; TextInfo txtInfo = new CultureInfo("en-us", false).TextInfo; functionName = txtInfo.ToTitleCase(functionName).Replace('_', ' ').Replace(" ", String.Empty); Console.Out.WriteLine(functionName); Console.ReadLine(); } }
Results: ZebulansNightmare
Desired Results: zebulansNightmare
UPDATE:
class Program { static void Main(string[] args) { string functionName = "zebulans_nightmare"; TextInfo txtInfo = new CultureInfo("en-us", false).TextInfo; functionName = txtInfo.ToTitleCase(functionName).Replace("_", string.Empty).Replace(" ", string.Empty); functionName = $"{functionName.First().ToString().ToLowerInvariant()}{functionName.Substring(1)}"; Console.Out.WriteLine(functionName); Console.ReadLine(); } }
Produces the desired output
To make titlecased version of a string, you use the string title() method. The title() returns a copy of a string in the titlecase. The title() method converts the first character of each words to uppercase and the remaining characters in lowercase.
In camel casing, two or more words are placed together without any space or underscore ( _ ), but the first letter of the first word is in lowercase and the first letter of the next word is capitalized.
You just need to lower the first char in the array. See this answer
Char.ToLowerInvariant(name[0]) + name.Substring(1)
As a side note, seeing as you are removing spaces you can replace the underscore with an empty string.
.Replace("_", string.Empty)
Implemented Bronumski's answer in an extension method (without replacing underscores).
public static class StringExtension { public static string ToCamelCase(this string str) { if(!string.IsNullOrEmpty(str) && str.Length > 1) { return char.ToLowerInvariant(str[0]) + str.Substring(1); } return str; } } //Or public static class StringExtension { public static string ToCamelCase(this string str) => string.IsNullOrEmpty(str) || str.Length < 2 ? str : char.ToLowerInvariant(str[0]) + str.Substring(1); }
and to use it:
string input = "ZebulansNightmare"; string output = input.ToCamelCase();
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