简体   繁体   中英

Replace character in string with Uppercase of next in line (Pascal Casing)

I want to remove all underscores from a string with the uppercase of the character following the underscore. So for example: _my_string_ becomes: MyString similarly: my_string becomes MyString

Is there a simpler way to do it? I currently have the following (assuming no input has two consecutive underscores):

        StringBuilder sb = new StringBuilder();
        int i;
        for (i = 0; i < input.Length - 1; i++)
        {
            if (input[i] == '_')
                sb.Append(char.ToUpper(input[++i]));
            else if (i == 0)
                sb.Append(char.ToUpper(input[i]));
            else
                sb.Append(input[i]);
        }
        if (i < input.Length && input[i] != '_')
            sb.Append(input[i]);

        return sb.ToString();

Now I know this is not totally related, but I thought to run some numbers on the implementations provided in the answers, and here are the results in Milliseconds for each implementation using 1000000 iterations of the string: "_my_string_121_a_" :

Achilles: 313
Raj: 870
Damian: 7916
Dmitry: 5380
Equalsk: 574

method utilised:

        Stopwatch stp = new Stopwatch();
        stp.Start();
        for (int i = 0; i < 1000000; i++)
        {
            sb = Test("_my_string_121_a_");
        }
        stp.Stop();
        long timeConsumed= stp.ElapsedMilliseconds;

In the end I think I'll go with Raj's implementation, because it's just very simple and easy to understand.

This must do it using ToTitleCase using System.Globalization namespace

static string toCamel(string input)
{        
    TextInfo info = CultureInfo.CurrentCulture.TextInfo;
    input= info.ToTitleCase(input).Replace("_", string.Empty);
    return input;
} 

在此输入图像描述

Shorter ( regular expressions ), but I doubt if it's better (regular expressions are less readable):

  string source = "_my_string_123__A_";

  // MyString123A  
  string result = Regex
     // _ + lower case Letter -> upper case letter (thanks to Wiktor Stribiżew)
    .Replace(source, @"(_+|^)(\p{Ll})?", match => match.Groups[2].Value.ToUpper())
     // all the other _ should be just removed
    .Replace("_", "");

Loops over each character and converts to uppercase as necessary.

public string GetNewString(string input)
{
    var convert = false;
    var sb = new StringBuilder();

    foreach (var c in input)
    {
        if (c == '_')
        {
            convert = true;
            continue;
        }

        if (convert)
        {
            sb.Append(char.ToUpper(c));
            convert = false;
            continue;
        }

        sb.Append(c);
    }

    return sb.ToString().First().ToString().ToUpper() + sb.ToString().Substring(1);
}

Usage:

GetNewString("my_string");
GetNewString("___this_is_anewstring_");
GetNewString("___this_is_123new34tring_");

Output:

MyString
ThisIsAnewstring
ThisIs123new34tring

Try with Regex:

var regex = new Regex("^[a-z]|_[a-z]?");
var result = regex.Replace("my_string_1234", x => x.Value== "_" ? "" : x.Value.Last().ToString().ToUpper());

Tested with:

my_string   -> MyString
_my_string  -> MyString
_my_string_ -> MyString

You need convert snake case to camel case, You can use this code it's working for me

  var x ="_my_string_".Split(new[] {"_"}, StringSplitOptions.RemoveEmptyEntries)
                .Select(s => char.ToUpperInvariant(s[0]) + s.Substring(1, s.Length - 1))
                .Aggregate(string.Empty, (s1, s2) => s1 + s2);

x = MyString

在此输入图像描述

    static string toCamel(string input)
    {
        StringBuilder sb = new StringBuilder();
        int i;
        for (i = 0; i < input.Length; i++)
        {
            if ((i == 0) || (i > 0 && input[i - 1] == '_'))
                sb.Append(char.ToUpper(input[i]));
            else
                sb.Append(char.ToLower(input[i]));
        }
        return sb.ToString();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM