将字符串转换为来自TitleCase C#的camelCase

我有一个字符串,我转换为TextInfo.ToTitleCase并删除了下划线并将字符串连接在一起。 现在我需要将字符串中的第一个字符和第一个字符更改为小写字母,由于某种原因,我无法弄清楚如何完成它。 在此先感谢您的帮助。

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(); } } 

结果:ZebulansNightmare

期望的结果:zebulansNightmare

更新:

 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(); } } 

产生所需的输出

您只需要降低数组中的第一个char。 看到这个答案

 Char.ToLowerInvariant(name[0]) + name.Substring(1) 

作为旁注,当您删除空格时,您可以用空字符串替换下划线。

 .Replace("_", string.Empty) 

在扩展方法中实现了Bronumski的答案(不替换下划线)。

  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; } } 

并使用它:

 string input = "ZebulansNightmare"; string output = input.ToCamelCase(); 

这是我的代码,以防它对任何人都有用

  // This converts to camel case // Location_ID => LocationId, and testLEFTSide => TestLeftSide static string CamelCase(string s) { var x = s.Replace("_", ""); if (x.Length == 0) return "Null"; x = Regex.Replace(x, "([AZ])([AZ]+)($|[AZ])", m => m.Groups[1].Value + m.Groups[2].Value.ToLower() + m.Groups[3].Value); return char.ToUpper(x[0]) + x.Substring(1); } 

最后一行将第一个char更改为大写,但您可以更改为小写或任何您喜欢的。

 public static string ToCamelCase(this string text) { return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(te); } public static string ToCamelCase(this string text) { return String.Join(" ", text.Split() .Select(i => Char.ToUpper(i[0]) + i.Substring(1)));} public static string ToCamelCase(this string text) { char[] a = text.ToLower().ToCharArray(); for (int i = 0; i < a.Count(); i++ ) { a[i] = i == 0 || a[i-1] == ' ' ? char.ToUpper(a[i]) : a[i]; } return new string(a);}