using Quasar.Common.Utilities; using System.Text; using System.Text.RegularExpressions; namespace Quasar.Common.Helpers { public static class StringHelper { /// /// Available alphabet for generation of random strings. /// private const string Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; /// /// Abbreviations of file sizes. /// private static readonly string[] Sizes = { "B", "KB", "MB", "GB", "TB", "PB" }; /// /// Random number generator. /// private static readonly SafeRandom Random = new SafeRandom(); /// /// Gets a random string with given length. /// /// The length of the random string. /// A random string. public static string GetRandomString(int length) { StringBuilder randomName = new StringBuilder(length); for (int i = 0; i < length; i++) randomName.Append(Alphabet[Random.Next(Alphabet.Length)]); return randomName.ToString(); } /// /// Gets the human readable file size for a given size. /// /// The file size in bytes. /// The human readable file size. public static string GetHumanReadableFileSize(long size) { double len = size; int order = 0; while (len >= 1024 && order + 1 < Sizes.Length) { order++; len = len / 1024; } return $"{len:0.##} {Sizes[order]}"; } /// /// Gets the formatted MAC address. /// /// The unformatted MAC address. /// The formatted MAC address. public static string GetFormattedMacAddress(string macAddress) { return (macAddress.Length != 12) ? "00:00:00:00:00:00" : Regex.Replace(macAddress, "(.{2})(.{2})(.{2})(.{2})(.{2})(.{2})", "$1:$2:$3:$4:$5:$6"); } /// /// Safely removes the last N chars from a string. /// /// The input string. /// The amount of last chars to remove (=N). /// The input string with N removed chars. public static string RemoveLastChars(string input, int amount = 2) { if (input.Length > amount) input = input.Remove(input.Length - amount); return input; } } }