using System; using System.Linq; using System.Text; namespace DiscordRPC.Helper { /// /// Collectin of helpful string extensions /// public static class StringTools { /// /// Will return null if the string is whitespace, otherwise it will return the string. /// /// The string to check /// Null if the string is empty, otherwise the string public static string GetNullOrString(this string str) { return str.Length == 0 || string.IsNullOrEmpty(str.Trim()) ? null : str; } /// /// Does the string fit within the given amount of bytes? Uses UTF8 encoding. /// /// The string to check /// The maximum number of bytes the string can take up /// True if the string fits within the number of bytes public static bool WithinLength(this string str, int bytes) { return str.WithinLength(bytes, Encoding.UTF8); } /// /// Does the string fit within the given amount of bytes? /// /// The string to check /// The maximum number of bytes the string can take up /// The encoding to count the bytes with /// True if the string fits within the number of bytes public static bool WithinLength(this string str, int bytes, Encoding encoding) { return encoding.GetByteCount(str) <= bytes; } /// /// Converts the string into UpperCamelCase (Pascal Case). /// /// The string to convert /// public static string ToCamelCase(this string str) { if (str == null) return null; return str.ToLower() .Split(new[] { "_", " " }, StringSplitOptions.RemoveEmptyEntries) .Select(s => char.ToUpper(s[0]) + s.Substring(1, s.Length - 1)) .Aggregate(string.Empty, (s1, s2) => s1 + s2); } /// /// Converts the string into UPPER_SNAKE_CASE /// /// The string to convert /// public static string ToSnakeCase(this string str) { if (str == null) return null; var concat = string.Concat(str.Select((x, i) => i > 0 && char.IsUpper(x) ? "_" + x.ToString() : x.ToString()).ToArray()); return concat.ToUpper(); } } }