簡體   English   中英

將字符串從 TitleCase C# 轉換為駝峰式

[英]Convert String To camelCase from TitleCase C#

我有一個字符串,我將其轉換為 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.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;
     }
 }

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

如果您使用 .NET Core 3 或 .NET 5,您可以調用:

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

那么你肯定會得到與 ASP.NET 自己的 JSON 序列化器相同的結果。

這是我的代碼,以防它對任何人有用

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

以下代碼也適用於首字母縮略詞。 如果它是第一個字其轉換的縮寫為小寫(例如, 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;
            });

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

改編自萊昂納多的回答

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,首先在任何大寫字母組之前添加一個空格,然后在刪除所有空格之前轉換為標題大小寫。

這是我的代碼,包括降低所有上前綴:

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();
var camelCaseFormatter = new JsonSerializerSettings();
camelCaseFormatter.ContractResolver = new CamelCasePropertyNamesContractResolver();

JsonConvert.SerializeObject(object, camelCaseFormatter));

這是我的代碼,非常簡單。 我的主要目標是確保駝峰式外殼與 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();
    }
}

字符串是不可變的,但我們可以使用不安全的代碼使其可變。 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;
        }

為什么要使用不安全的代碼? 簡短的回答......它超級快。

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

如果您對 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

我使用此方法將用“_”分隔的字符串轉換為駱駝大小寫

public static string ToCamelCase(string? s)
        {
            var nameArr = s?.ToLower().Split("_");
            var str = "";
            foreach (var name in nameArr.Select((value, i) => new { value, i }))
            {
                if(name.i >= 1)
                {
                    str += string.Concat(name.value[0].ToString().ToUpper(), name.value.AsSpan(1));
                }
                else
                {
                    str += name.value ;
                }
            }
            return str;
        }

你可以用“_”分隔任何你想要的。

構建簡單易行 c#

using System;
using System.Globalization;

public class SamplesTextInfo  {

   public static void Main()  {

      // Defines the string with mixed casing.
      string myString = "wAr aNd pEaCe";

      // Creates a TextInfo based on the "en-US" culture.
      TextInfo myTI = new CultureInfo("en-US",false).TextInfo;

      // Changes a string to lowercase.
      Console.WriteLine( "\"{0}\" to lowercase: {1}", myString, myTI.ToLower( myString ) );

      // Changes a string to uppercase.
      Console.WriteLine( "\"{0}\" to uppercase: {1}", myString, myTI.ToUpper( myString ) );

      // Changes a string to titlecase.
      Console.WriteLine( "\"{0}\" to titlecase: {1}", myString, myTI.ToTitleCase( myString ) );
   }
}

/*
This code produces the following output.

"wAr aNd pEaCe" to lowercase: war and peace
"wAr aNd pEaCe" to uppercase: WAR AND PEACE
"wAr aNd pEaCe" to titlecase: War And Peace

*/

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

In.Net 6及以上

public static class CamelCaseExtension
{
  public static string ToCamelCase(this string str) => 
     char.ToLowerInvariant(str[0]) + str[1..];
}

我對 titleCase 有同樣的問題,所以我剛剛創建了一個,希望這有助於這是一種擴展方法。

    public static string ToCamelCase(this string text)
    {
        if (string.IsNullOrEmpty(text))
            return text;

        var separators = new[] { '_', ' ' };
        var arr = text
            .Split(separators)
            .Where(word => !string.IsNullOrWhiteSpace(word));

        var camelCaseArr = arr
            .Select((word, i) =>
            {
                if (i == 0)
                    return word.ToLower();

                var characterArr = word.ToCharArray()
                    .Select((character, characterIndex) => characterIndex == 0
                        ? character.ToString().ToUpper()
                        : character.ToString().ToLower());

                return string.Join("", characterArr);
            });

        return string.Join("", camelCaseArr);
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM