tags:

views:

69

answers:

2

Anyone know of a nice efficient function that could convert, for example:
HelloWorld --> Hello World
helloWorld --> Hello World
Hello_World --> Hello World
hello_World --> Hello World

It would be nice to be able to handle all these situations.

Preferably in in VB.Net, or C#.

A: 

Sounded fun so I coded it the most important part is the regex take a look at this site for more documentation.

private static string BreakUpCamelCase(string s)
{
    MatchCollection MC = Regex.Matches(s, @"[0-9a-z][A-Z]");
    int LastMatch = 0;
    System.Text.StringBuilder SB = new StringBuilder();
    foreach (Match M in MC)
    {
        SB.AppendFormat("{0} ", s.Substring(LastMatch, M.Index + 1 - LastMatch));
        LastMatch = M.Index + 1;
    }
    if (LastMatch < s.Length)
    {
        SB.AppendFormat("{0} ", s.Substring(LastMatch));
    }
    return SB.ToString();
}
rerun
I see that you are hoarding your punctuation. Once everyone else has used up all the punctuation they have, you will be rich! Clever...
spong
+4  A: 

I don´t know if this is the most efficient way. But this method works fine:

EDIT 1: I have include Char.IsUpper suggestion in the comments

EDIT 2: included another suggestion in the comments: ToCharArray is superfluous because string implements enumerable ops as a char too, i.e. foreach (char character in input)

EDIT 3: I've used StringBuilder, like @Dan commented.

    public string CamelCaseToTextWithSpaces(string input)
    {


        StringBuilder output = new StringBuilder();

        input = input.Replace("_", "");

        foreach (char character in input)
        {
            if (char.IsUpper(character))
            { 
                output.Append(' ');             
            }

            if (output.Length == 0)
            {
                // The first letter must be always UpperCase
                output.Append(Char.ToUpper(character));
            }
            else
            {
                output.Append(character);
            }                
        }

        return output.ToString().Trim();
    }
Javier Morillo
`char.IsUpper(character)`
Paul Kohler
Thanks @Paul I´ve included it
Javier Morillo
Nice revision, BTW, the ToCharArray is superfluous because string implements enumerable ops as a char too, i.e. `foreach (char character in input)`.The reason I am watching this thread is the the moment it was asked I needed a "pascal case to human readable text" snippet in my code. I love stackoverflow!! :-)
Paul Kohler
Thanks again! I´ve updated the answer ^_^
Javier Morillo
@Javier: You should probably use the `StringBuilder` class for this; every time you have `output += something` you're creating a whole new string object, whereas `StringBuilder` has the ability to append to itself.
Dan Tao
LOL - it became a code review :-) Nice work @Javier
Paul Kohler
hehehe yeah :-) Thanks @Dan, too.
Javier Morillo