Splitting CamelCase

前端 未结 15 2498
盖世英雄少女心
盖世英雄少女心 2020-12-07 10:56

This is all asp.net c#.

I have an enum

public enum ControlSelectionType 
{
    NotApplicable = 1,
    SingleSelectRadioButtons = 2,
    SingleSelectD         


        
15条回答
  •  一个人的身影
    2020-12-07 11:51

    Simple version similar to some of the above, but with logic to not auto-insert the separator (which is by default, a space, but can be any char) if there's already one at the current position.

    Uses a StringBuilder rather than 'mutating' strings.

    public static string SeparateCamelCase(this string value, char separator = ' ') {
    
        var sb = new StringBuilder();
        var lastChar = separator;
    
        foreach (var currentChar in value) {
    
            if (char.IsUpper(currentChar) && lastChar != separator)
                sb.Append(separator);
    
            sb.Append(currentChar);
    
            lastChar = currentChar;
        }
    
        return sb.ToString();
    }
    

    Example:

    Input  : 'ThisIsATest'
    Output : 'This Is A Test'
    
    Input  : 'This IsATest'
    Output : 'This Is A Test' (Note: Still only one space between 'This' and 'Is')
    
    Input  : 'ThisIsATest' (with separator '_')
    Output : 'This_Is_A_Test'
    

提交回复
热议问题