开发者

Function to convert "camel case" type text to text with spaces in between? ie: HelloWorld --> Hello World

开发者 https://www.devze.com 2022-12-22 18:56 出处:网络
Anyone know of a nice efficient function that could convert, for example: HelloWorld -->Hello World helloWorld -->开发者_运维问答Hello World

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#.


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


There are some other possibilities you might want to cater for - for instance, you probably don't want to add spaces to abbreviations/acronyms.

I'd recommend using:

Private CamelCaseConverter As Regex = New Regex("(?<char1>[0-9a-z])(?<char2>[A-Z])", RegexOptions.Compiled + RegexOptions.CultureInvariant)

Public Function CamelCaseToWords(CamelCaseString As String) As String
 Return CamelCaseConverter.Replace(CamelCaseString, "${char1} ${char2}")
End Function

'Gives:
'CamelCase => Camel Case
'PIN => PIN

What it doesn't do is uppercase the first letter of the first word, but you can look at the other examples for ways of doing that, or maybe someone can come up with a clever RegEx way of doing it.


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();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消