83

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

产生所需的输出

4

14 回答 14

125

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

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

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

.Replace("_", string.Empty)
于 2017-02-18T03:28:21.097 回答
40

在扩展方法中实现了 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();
于 2018-05-30T14:45:09.380 回答
30

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

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

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

于 2021-02-23T22:34:29.010 回答
16

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

    // 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);
    }
于 2018-04-27T16:04:55.400 回答
9

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

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;
            });
于 2019-11-14T09:39:42.717 回答
5

示例 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);
    }
于 2018-08-16T14:48:54.377 回答
2

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

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();
于 2019-12-23T11:42:00.680 回答
1
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

于 2019-04-10T15:11:26.037 回答
1

改编自莱昂纳多的回答

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。

于 2019-06-27T13:31:43.493 回答
1
var camelCaseFormatter = new JsonSerializerSettings();
camelCaseFormatter.ContractResolver = new CamelCasePropertyNamesContractResolver();

JsonConvert.SerializeObject(object, camelCaseFormatter));
于 2020-04-18T06:26:04.180 回答
1

字符串是不可变的,但我们可以使用不安全的代码使其可变。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 注释警告用户。

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

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

于 2020-06-18T20:01:37.027 回答
1

这是我的代码,非常简单。我的主要目标是确保 camel-casing 与 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();
    }
}
于 2020-06-24T03:57:32.770 回答
1

如果你对 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

于 2021-10-17T03:51:49.927 回答
0
    /// <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;
    }
于 2021-08-11T10:09:56.047 回答