Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 694
Faheem Avatar asked Dec 01 '22 12:12

Faheem


1 Answers

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

enter image description here

like image 90
Rajshekar Reddy Avatar answered Dec 04 '22 23:12

Rajshekar Reddy