Code/Util/StringExtensions.cs
#nullable enable
using System.Globalization;

namespace Nodebox.Util;

public static class StringExtensions {
    /// <summary>
    /// Capitalizes the first character of the string using the provided culture (or current culture if null).
    /// Returns null if the input is null, and returns the original string if empty.
    /// </summary>
    public static string? CapitalizeFirstLetter(this string? value, CultureInfo? culture = null) {
        if (string.IsNullOrEmpty(value)) {
            return value;
        }

        culture ??= CultureInfo.CurrentCulture;
        char first = value[0];
        char upperFirst = char.ToUpper(first, culture);

        if (upperFirst == first) {
            return value;
        }

        if (value.Length == 1) {
            return new string(upperFirst, 1);
        }

        return upperFirst + value.Substring(1);
    }
}