将带下划线的字符串转换为TitleCase

问题描述 投票:0回答:6

鉴于此字符串:“EMAIL_LOG”

我想将其转换为:EmailLog

我有这个代码可以完成这项工作:

private static string TitleCaseConvert(string title)
{
    CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
    TextInfo textInfo = cultureInfo.TextInfo;
    title = title.Replace("_", " ").ToLower();
    title = textInfo.ToTitleCase(title);
    title = title.Replace(" ", "");
    return title;
}

我只是想知道是否有更好的建议来进行这种转换或者更优雅的建议?

谢谢。

c# string
6个回答
1
投票

如何在一个语句中完成它,如下所示:

private static string TitleCaseConvert(string title)
{ 
   return new CultureInfo("en").TextInfo.ToTitleCase(title.ToLower().Replace("_", " ")).Replace(" ", "");
}

2
投票

您可以使用Split()拆分_字符和StringBuilder来重建输出字符串。这应该会更好,因为你使用StringBuilder而不是每次都构造新的字符串:

private static string ToPascalCase(string input)
{
    if(input == null)
    {
        throw new ArgumentNullException("input");
    }

    TextInfo textInfo = CultureInfo.CurrentCulture.TextInfo;

    var sb = new StringBuilder();
    foreach(var part in input.Split('_'))
    {
        sb.Append(textInfo.ToTitleCase(part.ToLower()));
    }

    return sb.ToString();
}

请注意,我使用的是CultureInfo.CurrentCulture静态属性。我认为它更准确地描述了你想要的......

小提琴here


0
投票

如果你是在原始性能之后,你可以直接在char数组上操作:

private static string TitleCaseConvert(string title)
{
    int wordStart = 0;

    char[] result = new char[title.Length];
    int ri = 0;
    for (int i = 0; i < title.Length; ++i)
    {
        if (title[i] == '_')
        {
            wordStart = i + 1;
        }
        else if (i == wordStart)
        {
            result[ri++] = Char.ToUpper(title[i]);
        }
        else
        {
            result[ri++] = Char.ToLower(title[i]);
        }
    }

    return new String(result, 0, ri);
}

否则,StringBuilder实现可能会更短,更易读。


0
投票

你可以在这件事上扔Regex.Replace()来挑出第一个字符,转储下划线并将其大写。

title = Regex.Replace("this_is_a_test", @"(^|_)([a-z])", m =>  m.ToString().Replace("_","").ToUpper());

0
投票

使用Microsoft.VisualStudio的替代方案:

var title = Strings.StrConv("EMAIL_LOG", VbStrConv.ProperCase).Replace("_", "");

使用Humanizer库:

var title = "EMAIL_LOG".ToLower().Pascalize();

-1
投票

您在任何库中都有_.camelCase函数lodash

_.camelCase("EMAIL_LOG") // "emailLog"

我们添加(也来自lodash_.upperFirst函数将第一个字符设为大写。

_.upperFirst( _.camelCase("EMAIL_LOG") ) // "EmailLog"

骆驼香烟盒

骆驼案是写复合词或短语的做法,这样短语中间的每个词或缩写都以大写字母开头,没有插入空格或标点符号。

洛兹

Lodash是一个JavaScript库,它使用函数式编程范例为常见的编程任务提供实用程序功能。

© www.soinside.com 2019 - 2024. All rights reserved.