Best way to convert Pascal Case to a sentence

后端 未结 16 1939
天命终不由人
天命终不由人 2020-12-08 13:00

What is the best way to convert from Pascal Case (upper Camel Case) to a sentence.

For example starting with

\"AwaitingFeedback\"

a

16条回答
  •  情歌与酒
    2020-12-08 13:36

    Most of the preceding answers split acronyms and numbers, adding a space in front of each character. I wanted acronyms and numbers to be kept together so I have a simple state machine that emits a space every time the input transitions from one state to the other.

        /// 
        /// Add a space before any capitalized letter (but not for a run of capitals or numbers)
        /// 
        internal static string FromCamelCaseToSentence(string input)
        {
            if (string.IsNullOrEmpty(input)) return String.Empty;
    
            var sb = new StringBuilder();
            bool upper = true;
    
            for (var i = 0; i < input.Length; i++)
            {
                bool isUpperOrDigit = char.IsUpper(input[i]) || char.IsDigit(input[i]);
                // any time we transition to upper or digits, it's a new word
                if (!upper && isUpperOrDigit)
                {
                    sb.Append(' ');
                }
                sb.Append(input[i]);
                upper = isUpperOrDigit;
            }
    
            return sb.ToString();
        }
    

    And here's some tests:

        [TestCase(null, ExpectedResult = "")]
        [TestCase("", ExpectedResult = "")]
        [TestCase("ABC", ExpectedResult = "ABC")]
        [TestCase("abc", ExpectedResult = "abc")]
        [TestCase("camelCase", ExpectedResult = "camel Case")]
        [TestCase("PascalCase", ExpectedResult = "Pascal Case")]
        [TestCase("Pascal123", ExpectedResult = "Pascal 123")]
        [TestCase("CustomerID", ExpectedResult = "Customer ID")]
        [TestCase("CustomABC123", ExpectedResult = "Custom ABC123")]
        public string CanSplitCamelCase(string input)
        {
            return FromCamelCaseToSentence(input);
        }
    

提交回复
热议问题