【问题标题】:Convert String To camelCase from TitleCase C#将字符串从 TitleCase C# 转换为 camelCase
【发布时间】:2024-01-09 14:24:02
【问题描述】:

我有一个字符串,我将其转换为 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();
    }
}

产生所需的输出

【问题讨论】:

  • 您应该只发布自己的答案,而不是在问题中提出解决方案,这样会更混乱。

标签: c# camelcasing tolower title-case


【解决方案1】:

您只需要降低数组中的第一个字符。看到这个answer

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

附带说明,当您删除空格时,您可以将下划线替换为空字符串。

.Replace("_", string.Empty)

【讨论】:

  • 谢谢我所需要的。
  • 好电话。进行了调整并更新了问题。
  • 这不适用于开头的首字母缩略词(例如,VATReturnAmount)。见my answer
  • 同意@Mojtaba。如果您想与 ASP.NET 中的 camelCase JSON 序列化兼容,请不要使用它。开头的首字母缩写词不会一样。
【解决方案2】:

在扩展方法中实现了 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;
     }
 }

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

并使用它:

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

【讨论】:

  • 我看到的唯一问题是字符串是否只是“A”。它应该返回“a”,对吧?
【解决方案3】:

如果您使用的是 .NET Core 3 或 .NET 5,您可以调用:

System.Text.Json.JsonNamingPolicy.CamelCase.ConvertName(someString)

那么你肯定会得到与 ASP.NET 自己的 JSON 序列化器相同的结果。

【讨论】:

  • 这对我不起作用,它在我的情况下将所有内容都转换为小写
  • 请注意,这不会删除空格,因此您需要执行 JsonNamingPolicy.CamelCase.ConvertName(str).Replace(" ", string.Empty)
【解决方案4】:

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

    // 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, "([A-Z])([A-Z]+)($|[A-Z])",
            m => m.Groups[1].Value + m.Groups[2].Value.ToLower() + m.Groups[3].Value);
        return char.ToLower(x[0]) + x.Substring(1);
    }

如果您更喜欢 Pascal-case 使用:

    static string PascalCase(string s)
    {
        var x = CamelCase(s);
        return char.ToUpper(x[0]) + x.Substring(1);
    }

【讨论】:

  • 最后是一个将MYCase转换为myCase的例子,而不是myCase。谢谢!
  • @MusterStation 但是为什么呢?您不应该首先拥有“MyCase”吗?如果“Y”是大写的,那么它可能是另一个词,对吧?
  • @ygoe 也许吧。在“MYCase”中,M 是一个词,Y 是一个词,Case 是一个词。但是,“MY”更有可能是两个字母的首字母缩写词。例如“innerHTML”是两个词,而不是五个。
  • 这转换为 PascalCase 而不是 camelCase
  • @CraigShearer 是的....如果你想要camelCase,最后一行可以是ToLower
【解决方案5】:

以下代码也适用于首字母缩略词。如果它是第一个单词,它将首字母缩写词转换为小写(例如,VATReturnvatReturn),否则保持原样(例如,ExcludedVATexcludedVAT)。

name = Regex.Replace(name, @"([A-Z])([A-Z]+|[a-z0-9_]+)($|[A-Z]\w*)",
            m =>
            {
                return m.Groups[1].Value.ToLower() + m.Groups[2].Value.ToLower() + m.Groups[3].Value;
            });

【讨论】:

  • 谢谢,这样好多了。当您 return Json(new { CAPSItem = ... } 时,它与 MVC 的行为相匹配,而接受的答案将产生不匹配
  • 如果您必须从 camelCase 转换回 PascalCase,就会出现首字母缩略词问题。例如,我看不到如何将vatReturn 转换回VATReturn。最好使用VatReturn 作为您的pascal 命名约定,然后您可以坚持只修改第一个字母。
  • @HappyNomad 尽管您的观点在其上下文中是有效的,但问题是关于转换为 camelCase;这意味着使用VatReturn 而不是vatReturn 作为首字母缩略词不是这个问题的答案。
【解决方案6】:

示例 01

    public static string ToCamelCase(this string text)
    {
        return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(text);
    }

示例 02

public static string ToCamelCase(this string text)
    {
        return string.Join(" ", text
                            .Split()
                            .Select(i => char.ToUpper(i[0]) + i.Substring(1)));
    }

示例 03

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

【讨论】:

  • 欢迎来到 *!虽然这可能会回答问题,但请考虑添加文字说明为什么这是一个合适的答案以及支持您的答案的链接!
  • 鉴于没有其他答案有文章支持答案并且只有一个有链接,我认为这有点苛刻,或者非常“*-ish”。肯尼给出的第一个答案是一个很好的回答 imo(尽管我同意 te to text 有错字)。
  • 这太苛刻了?
  • @CodeWarrior 不,不是。不过,他本可以说“请”。顺便说一句,代码风格看起来很丑(可能不只是对我来说),难以阅读。
  • 最重要的是它甚至没有回答这个问题。它转换为 TitleCase,这不是问题。
【解决方案7】:

这是我的代码,包括降低所有高位前缀:

public static class StringExtensions
{
    public static string ToCamelCase(this string str)
    {
        bool hasValue = !string.IsNullOrEmpty(str);

        // doesn't have a value or already a camelCased word
        if (!hasValue || (hasValue && Char.IsLower(str[0])))
        {
            return str;
        }

        string finalStr = "";

        int len = str.Length;
        int idx = 0;

        char nextChar = str[idx];

        while (Char.IsUpper(nextChar))
        {
            finalStr += char.ToLowerInvariant(nextChar);

            if (len - 1 == idx)
            {
                // end of string
                break;
            }

            nextChar = str[++idx];
        }

        // if not end of string 
        if (idx != len - 1)
        {
            finalStr += str.Substring(idx);
        }

        return finalStr;
    }
}

像这样使用它:

string camelCasedDob = "DOB".ToCamelCase();

【讨论】:

  • 抱歉,这根本不是一个好的代码...连接字符串创建新字符串...在这种情况下,您创建的字符串与 str中的原始字符串一样多>。如果你有一个长字符串,GC 会讨厌你。
【解决方案8】:
public static string CamelCase(this string str)  
    {  
      TextInfo cultInfo = new CultureInfo("en-US", false).TextInfo;
      str = cultInfo.ToTitleCase(str);
      str = str.Replace(" ", "");
      return str;
    }

这应该使用 System.Globalization 工作

【讨论】:

  • 这很好,但不幸的是它会将PascalCase 转换为Pascalcase
【解决方案9】:

改编自莱昂纳多的answer

static string PascalCase(string str) {
  TextInfo cultInfo = new CultureInfo("en-US", false).TextInfo;
  str = Regex.Replace(str, "([A-Z]+)", " $1");
  str = cultInfo.ToTitleCase(str);
  str = str.Replace(" ", "");
  return str;
}

转换为 PascalCase,首先在任何一组大写字母之前添加一个空格,然后在删除所有空格之前转换为标题大小写。

【讨论】:

    【解决方案10】:
    var camelCaseFormatter = new JsonSerializerSettings();
    camelCaseFormatter.ContractResolver = new CamelCasePropertyNamesContractResolver();
    
    JsonConvert.SerializeObject(object, camelCaseFormatter));
    

    【讨论】:

    • 虽然这可能会回答这个问题,但如果您稍微解释一下您的代码会更有帮助。
    • 这是一个很奇怪的正向答案。您只需通过将其 contractresovler 选项设置为 Camelcase 来创建 JsonSerilizerSetting。因此,对象是您想要与设置一起序列化的任何内容。你可以自定义任何你想要的设置
    【解决方案11】:

    字符串是不可变的,但我们可以使用不安全的代码使其可变。 string.Copy 确保原始字符串保持原样。

    为了让这些代码运行,您必须在您的项目中允许不安全的代码

            public static unsafe string ToCamelCase(this string value)
            {
                if (value == null || value.Length == 0)
                {
                    return value;
                }
    
                string result = string.Copy(value);
    
                fixed (char* chr = result)
                {
                    char valueChar = *chr;
                    *chr = char.ToLowerInvariant(valueChar);
                }
    
                return result;
            }
    

    此版本修改原始字符串,而不是返回修改后的副本。这会很烦人,而且完全不常见。因此,请确保 XML cmets 会就此向用户发出警告。

            public static unsafe void ToCamelCase(this string value)
            {
                if (value == null || value.Length == 0)
                {
                    return value;
                }
    
                fixed (char* chr = value)
                {
                    char valueChar = *chr;
                    *chr = char.ToLowerInvariant(valueChar);
                }
    
                return value;
            }
    

    为什么要使用不安全的代码呢?简短的回答...超级快。

    【讨论】:

      【解决方案12】:

      这是我的代码,非常简单。我的主要目标是确保驼峰式大小写与 ASP.NET 将对象序列化到的内容兼容,而上述示例并不能保证这一点。

      public static class StringExtensions
      {
          public static string ToCamelCase(this string name)
          {
              var sb = new StringBuilder();
              var i = 0;
              // While we encounter upper case characters (except for the last), convert to lowercase.
              while (i < name.Length - 1 && char.IsUpper(name[i + 1]))
              {
                  sb.Append(char.ToLowerInvariant(name[i]));
                  i++;
              }
      
              // Copy the rest of the characters as is, except if we're still on the first character - which is always lowercase.
              while (i < name.Length)
              {
                  sb.Append(i == 0 ? char.ToLowerInvariant(name[i]) : name[i]);
                  i++;
              }
      
              return sb.ToString();
          }
      }
      

      【讨论】:

        【解决方案13】:

        如果你对 Newtonsoft.JSON 依赖没问题,下面的字符串扩展方法会有所帮助。这种方法的优点是序列化将与标准 WebAPI 模型绑定序列化相当,并且准确度高。

        public static class StringExtensions
        {
            private class CamelCasingHelper : CamelCaseNamingStrategy
            {
                private CamelCasingHelper(){}
                private static CamelCasingHelper helper =new CamelCasingHelper();
                public static string ToCamelCase(string stringToBeConverted)
                {
                    return helper.ResolvePropertyName(stringToBeConverted);     
                }
                
            }
            public static string ToCamelCase(this string str)
            {
                return CamelCasingHelper.ToCamelCase(str);
            }
        }
        

        这是工作小提琴 https://dotnetfiddle.net/pug8pP

        【讨论】:

          【解决方案14】:
              /// <summary>
              /// Gets the camel case from snake case.
              /// </summary>
              /// <param name="snakeCase">The snake case.</param>
              /// <returns></returns>
              private string GetCamelCaseFromSnakeCase(string snakeCase)
              {
                  string camelCase = string.Empty;
          
                  if(!string.IsNullOrEmpty(snakeCase))
                  {
                      string[] words = snakeCase.Split('_');
                      foreach (var word in words)
                      {
                          camelCase = string.Concat(camelCase, Char.ToUpperInvariant(word[0]) + word.Substring(1));
                      }
          
                      // making first character small case
                      camelCase = Char.ToLowerInvariant(camelCase[0]) + camelCase.Substring(1);
                  }
          
                  return camelCase;
              }
          

          【讨论】:

          • 请添加一些描述或 cmets 以帮助他们。
          最近更新 更多