namespace Xorog.UniversalExtensions; public static class StringExtensions { /// /// Extensions for string.IsNullOrWhiteSpace /// /// /// Whether the string is null, empty or only contains whitespaces public static bool IsNullOrWhiteSpace(this string? str) => string.IsNullOrWhiteSpace(str); /// /// Extensions for string.IsNullOrEmpty /// /// /// Whether the string is null or empty public static bool IsNullOrEmpty(this string? str) => string.IsNullOrEmpty(str); /// /// Check if a string contains only digits /// /// /// public static bool IsDigitsOnly(this string str) { foreach (char c in str) { if (c is < '0' or > '9') return false; } return true; } /// /// Get all digits from a string /// /// /// public static string GetAllDigits(this string str) => new(str.Where(Char.IsDigit).ToArray()); /// /// Get country flag emoji based on Iso Country Code /// /// /// public static string IsoCountryCodeToFlagEmoji(this string country) { return string.Concat(country.ToUpper().Select(x => char.ConvertFromUtf32(x + 0x1F1A5))); } /// /// Shorten a string to the given length /// /// /// /// public static string Truncate(this string value, int maxLength) { if (string.IsNullOrEmpty(value)) return value; return value.Length <= maxLength ? value : value[..maxLength]; } /// /// Shorten a string to the given length and add ".." at the end /// /// /// /// public static string TruncateWithIndication(this string value, int maxLength) { if (string.IsNullOrEmpty(value)) return value; return value.Length <= maxLength ? value : $"{value[..(maxLength - 2)]}.."; } /// /// Remove unsupported characters from string to generate a valid filename /// /// The string with potentionally unwanted characters /// The character the unwanted characters get replaced with (default: _) /// A valid filename public static string MakeValidFileName(this string name, char replace_char = '_') { string invalidChars = System.Text.RegularExpressions.Regex.Escape(new string(System.IO.Path.GetInvalidFileNameChars())); string invalidRegStr = string.Format(@"([{0}]*\.+$)|([{0}]+)", invalidChars); return System.Text.RegularExpressions.Regex.Replace(name, invalidRegStr, replace_char.ToString()).Replace('&', replace_char); } /// /// Changes the first letter to upper. /// /// The string to modify. /// The string with the first letter changed to upper. public static string FirstLetterToUpper(this string str) { return $"{str.First().ToString().ToUpper()}{str.Remove(0, 1)}"; } }