将任何字符串转换为特定格式

huangapple go评论66阅读模式
英文:

Convert Any Sting To A Specific Format

问题

我正在尝试将一种字符串转换为驼峰命名法。这是字符串:

here %it -RAINS

期望的输出

hereItRains

我尝试了以下代码:

public static string ToCamelCase(this string str)
{
    var words = str.Split(new[] { "_", "-", "%" }, StringSplitOptions.RemoveEmptyEntries);

    words = words.Select(word => char.ToUpper(word[0]) + word.Substring(1)).ToArray();
    
    return string.Join(string.Empty, words);
}

得到的输出如下:

Here It RAINS

这里有什么我错过的地方吗?这是我迄今为止尝试的链接 - CamelCase

英文:

I am trying to convert a type of string into camel case. Here's the string:

here %it -RAINS

Expected Output:

hereItRains

I tried the following:

public static string ToCamelCase(this string str)
{
    var words = str.Split(new[] { "_", "-", "%" }, StringSplitOptions.RemoveEmptyEntries);

    words = words.Select(word => char.ToUpper(word[0]) + word.Substring(1)).ToArray();
    
	return string.Join(string.Empty, words);
}

Got the output as below:

Here It RAINS

Is there anything that I missed here? Here's the link that I tried so far - CamelCase

答案1

得分: 3

你已经有很多答案了,但我想再添加一个新的答案,使用原始的 C# 代码来处理字符串,避免一些内存分配并减少处理时间。

public static string ToCamelCase(this string value)
{
    if (string.IsNullOrWhiteSpace(value))
        return value;

    var upperCase = false;
    var sb = new StringBuilder();

    for (int i = 0; i < value.Length; i++)
    {
        if (char.IsWhiteSpace(value[i]) || char.IsPunctuation(value[i]))
        {
            upperCase = true;
            continue;
        }

        char ch;

        if (upperCase)
        {
            ch = char.ToUpperInvariant(value[i]);
        }
        else
        {
            ch = char.IsLower(value[i]) ? value[i] : char.ToLowerInvariant(value[i]);
        }

        upperCase = false;

        sb.Append(ch);
    }

    return sb.ToString();
}

当我们使用像 ToArray、Split、ToLower、Regex 等方法时,会在内存中创建许多对象,通过一些逻辑可以避免这种情况。

基准测试

将任何字符串转换为特定格式

英文:

You already have many answers here, but I would like to add a new one, which is using raw C# code to process the string, avoid some memory allocation and reduce processing time.

public static string ToCamelCase(this string value)
{
    if (string.IsNullOrWhiteSpace(value))
        return value;

    var upperCase = false;
    var sb = new StringBuilder();

    for (int i = 0; i &lt; value.Length; i++)
    {
        if (char.IsWhiteSpace(value[i]) || char.IsPunctuation(value[i]))
        {
            upperCase = true;
            continue;
        }

        char ch;

        if (upperCase)
        {
            ch = char.ToUpperInvariant(value[i]);
        }
        else
        {
            ch = char.IsLower(value[i]) ? value[i] : char.ToLowerInvariant(value[i]);
        }

        upperCase = false;

        sb.Append(ch);
    }

    return sb.ToString();
}

When we use methods like ToArray, Split, ToLower, Regex, etc, we are creating many objects in memory and this can be avoided with some logic.

Benchmark tests

将任何字符串转换为特定格式

答案2

得分: 2

我建议使用正则表达式来匹配所有需要转换为小写(第一个单词)或标题大小写(其余单词)的单词:

using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;

...

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

  return string.Concat(Regex
    .Matches(value, @"\p{L}+")
    .Select(match => match.Value.ToLower(CultureInfo.InvariantCulture))
    .Select((word, index) => index == 0
       ? word
       : CultureInfo.InvariantCulture.TextInfo.ToTitleCase(word)));
}

Fiddle

备注:

  1. \p{L}+ 模式代表“一个或多个Unicode字母”。
  2. ToTitleCase 将任何单词转换为标题大小写,除了全大写的单词(被视为首字母缩写词而不进行更改),这就是为什么我对任何单词调用 ToLower() 的原因。
英文:

I suggest using regular expressions in order to match all the words which we should turn into lower case (the very first word) or title case (all the rest words):

using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;

...

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

  return string.Concat(Regex
    .Matches(value, @&quot;\p{L}+&quot;)
    .Select(match =&gt; match.Value.ToLower(CultureInfo.InvariantCulture))
    .Select((word, index) =&gt; index == 0
       ? word
       : CultureInfo.InvariantCulture.TextInfo.ToTitleCase(word)));
}

Fiddle

Remarks:

  1. \p{L}+ pattern stands for "one or more Unicode letters".
  2. ToTitleCase turns any word into title case except all capital letters words (which are treated as acronyms and not changed), that's why I call ToLower() for any word.

答案3

得分: 1

我为我的大学作业编写了以下代码,并且它完美地运行了。ToCamelCase 函数接受一个输入文本,使用空格、下划线和连字符作为分隔符,将其分解为单词,然后将每个单词转换为标题大小写(将首字母大写),除了第一个单词。TextInfo 类根据当前的区域设置处理正确的大小写。

class Program
{
    static string ToCamelCase(string input)
    {
        TextInfo textInfo = new CultureInfo("en-US", false).TextInfo;
        string[] words = input.Split(new[] { ' ', '_', '-' }, StringSplitOptions.RemoveEmptyEntries);

        if (words.Length == 0)
            return input;

        string camelCase = words[0].ToLower();
        for (int i = 1; i < words.Length; i++)
        {
            camelCase += textInfo.ToTitleCase(words[i].ToLower());
        }

        return camelCase;
    }

    static void Main(string[] args)
    {
        string input = "convert_this_string_to_camel_case";
        string camelCaseOutput = ToCamelCase(input);

        Console.WriteLine(camelCaseOutput);
    }
}
英文:

I did the following code for one of my college assignment and it worked perfectly fine. The ToCamelCase function takes an input text, breaks it into words using spaces, underscores, and hyphens as delimiters, and then transforms each word to title case (capitalising the initial letter) except the first. The TextInfo class handles correct case depending on current culture.

class Program
{
    static string ToCamelCase(string input)
    {
        TextInfo textInfo = new CultureInfo(&quot;en-US&quot;, false).TextInfo;
        string[] words = input.Split(new[] { &#39; &#39;, &#39;_&#39;, &#39;-&#39; }, StringSplitOptions.RemoveEmptyEntries);

        if (words.Length == 0)
            return input;

        string camelCase = words[0].ToLower();
        for (int i = 1; i &lt; words.Length; i++)
        {
            camelCase += textInfo.ToTitleCase(words[i].ToLower());
        }

        return camelCase;
    }

    static void Main(string[] args)
    {
        string input = &quot;convert_this_string_to_camel_case&quot;;
        string camelCaseOutput = ToCamelCase(input);

        Console.WriteLine(camelCaseOutput);
    }
}

答案4

得分: 1

请注意,我将为您翻译以下内容:

编辑ToCamelCase函数如下:

public string ToCamelCase(string str)
{
    var allWords = str.Split(new[] { "_", "-", "%", " " }, StringSplitOptions.RemoveEmptyEntries).ToList();                      
    var words = allWords.Skip(1).Select(word => char.ToUpper(word[0]) + word.Substring(1).ToLower()).ToList();
    words.Insert(0, allWords[0]);
    return string.Join(string.Empty, words);
}
  1. &quot; &quot;添加到您的Split集合中。

  2. word.Substring(1)后添加.ToLower()

  3. 使用allWords.Skip(1)跳过第一个单词。

结果:

a b c %d ==> aBCD
here %it -RAINS ==> hereItRains

请注意,这是对代码进行的修改和结果示例。

英文:

Edit the ToCamelCase function as follows:

public string ToCamelCase(string str)
{
    var allWords = str.Split(new[] { &quot;_&quot;, &quot;-&quot;, &quot;%&quot;, &quot; &quot; }, StringSplitOptions.RemoveEmptyEntries).ToList();                      
    var words = allWords.Skip(1).Select(word =&gt; char.ToUpper(word[0]) + word.Substring(1).ToLower()).ToList();
    words.Insert(0, allWords[0]);
    return string.Join(string.Empty, words);
}
  1. add &quot; &quot; to your Split collection.

  2. add .ToLower() to word.Substring(1)

  3. skip the first word with allWords.Skip(1)

result:

a b c %d ==&gt; aBCD
here %it -RAINS ==&gt; hereItRains

huangapple
  • 本文由 发表于 2023年8月8日 19:59:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76859348.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定