ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

SplitOnUpperCase

Useful for display things like property names like FirstName to First Name.

Source

using System.Diagnostics;

namespace TODO;

internal static  class StringExtensions
{
    /// <summary>
    /// Split text at each capital letter
    /// </summary>
    /// <param name="input">string to work on</param>
    /// <returns>
    /// <para>An empty string, if the input is null or empty.</para>
    /// <para>Same as original if nothing affected</para>
    /// <para>String split on each uppercase token</para>
    /// <para>SSMS would become S S M S</para>
    /// </returns>
    [DebuggerStepThrough]
    public static string SplitOnUpperCase(this string input)
    {
        if (string.IsNullOrEmpty(input))
            return input;
  
        Span<char> result = stackalloc char[input.Length * 2];
        var resultIndex = 0;

        for (var index = 0; index < input.Length; index++)
        {
            var currentChar = input[index];

            if (index > 0 && char.IsUpper(currentChar))
            {
                result[resultIndex++] = ' ';
            }

            result[resultIndex++] = currentChar;
        }

        return result[..resultIndex].ToString();
    }

}

Example

string[] items = ["FirstName", "BirthDate", "", "ABC"];

foreach (var item in items)
{
    Console.WriteLine($"{item,-12}{item.SplitOnUpperCase()}");
}

// example for splitting property names
internal class Customer
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateOnly BirthDate { get; set; }
}

//
foreach (PropertyInfo p in typeof(Customer).GetProperties())
{
    Console.WriteLine($"{p.Name,-12}{p.Name.SplitOnUpperCase()}");
}

Author: Karen Payne

Submitted on: 30 jul. 2024

Language: csharp

Type: System.String

Views: 347