HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

Converting strings to PascalCase

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
convertingstringspascalcase

Problem

I have a method which I use on occasion to convert strings (like enum and property names) to PascalCase for display.

It's fairly simple, so there's probably not much to comment on, but as usual I appreciate any advice on improving it.

/// 
/// Converts a string of dash-separated, or underscore-separated words to a PascalCase string.
/// 
/// The string to convert.
/// The resulting PascalCase string.
public static string ToPascalCase(this string s)
{
    string[] words = s.Split(new char[2] { '-', '_' }, StringSplitOptions.RemoveEmptyEntries);

    StringBuilder sb = new StringBuilder(words.Sum(x => x.Length));

    foreach (string word in words)
    {
        sb.Append(word[0].ToString().ToUpper() + word.Substring(1));
    }

    return sb.ToString();
}


Feel free to use it if you like, as per my usual regards.

Solution

I think you should use Concat instead of StringBuilder:

public static string ToPascalCase(this string s)
{
    var words = s.Split(new[] { '-', '_' }, StringSplitOptions.RemoveEmptyEntries)
                 .Select(word => word.Substring(0, 1).ToUpper() + 
                                 word.Substring(1).ToLower());

    var result = String.Concat(words);
    return result;
}


This solution should not be as fast as manually looping through the original string, but I think it is much easier to read and follow. Unless you do those convertions like 1000000 times per second, you should not complicate things.

Code Snippets

public static string ToPascalCase(this string s)
{
    var words = s.Split(new[] { '-', '_' }, StringSplitOptions.RemoveEmptyEntries)
                 .Select(word => word.Substring(0, 1).ToUpper() + 
                                 word.Substring(1).ToLower());

    var result = String.Concat(words);
    return result;
}

Context

StackExchange Code Review Q#112769, answer score: 13

Revisions (0)

No revisions yet.