Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- namespace Coldwire.Text
- {
- using System;
- using System.Collections.Generic;
- using System.Globalization;
- using System.Text;
- using System.Text.RegularExpressions;
- public static class Strings
- {
- #region HtmlEntities
- private static readonly string[] htmlEntities = new[] {
- // Reserved (xml) entities
- "quot", "\"",
- "apos", "'",
- "amp", "&",
- "lt", "<",
- "gt", ">",
- // ISO-8859-1 entities
- "nbsp", "\u00a0",
- "iexcl", "¡",
- "cent", "¢",
- "pound", "£",
- "curren", "¤",
- "yen", "¥",
- "brvbar", "¦",
- "sect", "§",
- "uml", "¨",
- "copy", "©",
- "ordf", "ª",
- "laquo", "«",
- "not", "¬",
- "shy", "\u00ad",
- "reg", "®",
- "macr", "¯",
- "deg", "°",
- "plusmn", "±",
- "sup2", "²",
- "sup3", "³",
- "acute", "´",
- "micro", "µ",
- "para", "¶",
- "middot", "·",
- "cedil", "¸",
- "sup1", "¹",
- "ordm", "º",
- "raquo", "»",
- "frac14", "¼",
- "frac12", "½",
- "frac34", "¾",
- "iquest", "¿",
- "times", "×",
- "divide", "÷",
- "Agrave", "À",
- "Aacute", "Á",
- "Acirc", "Â",
- "Atilde", "Ã",
- "Auml", "Ä",
- "Aring", "Å",
- "AElig", "Æ",
- "Ccedil", "Ç",
- "Egrave", "È",
- "Eacute", "É",
- "Ecirc", "Ê",
- "Euml", "Ë",
- "Igrave", "Ì",
- "Iacute", "Í",
- "Icirc", "Î",
- "Iuml", "Ï",
- "ETH", "Ð",
- "Ntilde", "Ñ",
- "Ograve", "Ò",
- "Oacute", "Ó",
- "Ocirc", "Ô",
- "Otilde", "Õ",
- "Ouml", "Ö",
- "Oslash", "Ø",
- "Ugrave", "Ù",
- "Uacute", "Ú",
- "Ucirc", "Û",
- "Uuml", "Ü",
- "Yacute", "Ý",
- "THORN", "Þ",
- "szlig", "ß",
- "agrave", "à",
- "aacute", "á",
- "acirc", "â",
- "atilde", "ã",
- "auml", "ä",
- "aring", "å",
- "aelig", "æ",
- "ccedil", "ç",
- "egrave", "è",
- "eacute", "é",
- "ecirc", "ê",
- "euml", "ë",
- "igrave", "ì",
- "iacute", "í",
- "icirc", "î",
- "iuml", "ï",
- "eth", "ð",
- "ntilde", "ñ",
- "ograve", "ò",
- "oacute", "ó",
- "ocirc", "ô",
- "otilde", "õ",
- "ouml", "ö",
- "oslash", "ø",
- "ugrave", "ù",
- "uacute", "ú",
- "ucirc", "û",
- "uuml", "ü",
- "yacute", "ý",
- "thorn", "þ",
- "yuml", "ÿ",
- // Math symbols
- "forall", "∀",
- "part", "∂",
- "exist", "∃",
- "empty", "∅",
- "nabla", "∇",
- "isin", "∈",
- "notin", "∉",
- "ni", "∋",
- "prod", "∏",
- "sum", "∑",
- "minus", "−",
- "lowast", "∗",
- "radic", "√",
- "prop", "∝",
- "infin", "∞",
- "ang", "∠",
- "and", "∧",
- "or", "∨",
- "cap", "∩",
- "cup", "∪",
- "int", "∫",
- "there4", "∴",
- "sim", "∼",
- "cong", "≅",
- "asymp", "≈",
- "ne", "≠",
- "equiv", "≡",
- "le", "≤",
- "ge", "≥",
- "sub", "⊂",
- "sup", "⊃",
- "nsub", "⊄",
- "sube", "⊆",
- "supe", "⊇",
- "oplus", "⊕",
- "otimes", "⊗",
- "perp", "⊥",
- "sdot", "⋅",
- // Greek letters
- "Alpha", "Α",
- "Beta", "Β",
- "Gamma", "Γ",
- "Delta", "Δ",
- "Epsilon", "Ε",
- "Zeta", "Ζ",
- "Eta", "Η",
- "Theta", "Θ",
- "Iota", "Ι",
- "Kappa", "Κ",
- "Lambda", "Λ",
- "Mu", "Μ",
- "Nu", "Ν",
- "Xi", "Ξ",
- "Omicron", "Ο",
- "Pi", "Π",
- "Rho", "Ρ",
- "Sigma", "Σ",
- "Tau", "Τ",
- "Upsilon", "Υ",
- "Phi", "Φ",
- "Chi", "Χ",
- "Psi", "Ψ",
- "Omega", "Ω",
- "alpha", "α",
- "beta", "β",
- "gamma", "γ",
- "delta", "δ",
- "epsilon", "ε",
- "zeta", "ζ",
- "eta", "η",
- "theta", "θ",
- "iota", "ι",
- "kappa", "κ",
- "lambda", "λ",
- "mu", "μ",
- "nu", "ν",
- "xi", "ξ",
- "omicron", "ο",
- "pi", "π",
- "rho", "ρ",
- "sigmaf", "ς",
- "sigma", "σ",
- "tau", "τ",
- "upsilon", "υ",
- "phi", "φ",
- "chi", "χ",
- "psi", "ψ",
- "omega", "ω",
- "thetasym", "ϑ",
- "upsih", "ϒ",
- "piv", "ϖ",
- // Other entities
- "OElig", "Œ",
- "oelig", "œ",
- "Scaron", "Š",
- "scaron", "š",
- "Yuml", "Ÿ",
- "fnof", "ƒ",
- "circ", "ˆ",
- "tilde", "˜",
- "ensp", "\u2002",
- "emsp", "\u2003",
- "thinsp", "\u2009",
- "zwnj", "\u200c",
- "zwj", "\u200d",
- "lrm", "\u200e",
- "rlm", "\u200f",
- "ndash", "–",
- "mdash", "—",
- "lsquo", "‘",
- "rsquo", "’",
- "sbquo", "‚",
- "ldquo", "“",
- "rdquo", "”",
- "bdquo", "„",
- "dagger", "†",
- "Dagger", "‡",
- "bull", "•",
- "hellip", "…",
- "permil", "‰",
- "prime", "′",
- "Prime", "″",
- "lsaquo", "‹",
- "rsaquo", "›",
- "oline", "‾",
- "euro", "€",
- "trade", "™",
- "larr", "←",
- "uarr", "↑",
- "rarr", "→",
- "darr", "↓",
- "harr", "↔",
- "crarr", "↵",
- "lceil", "⌈",
- "rceil", "⌉",
- "lfloor", "⌊",
- "rfloor", "⌋",
- "loz", "◊",
- "spades", "♠",
- "clubs", "♣",
- "hearts", "♥",
- "diams", "♦",
- };
- #endregion
- private static readonly Dictionary<string, char> symbolsDecodeTable;
- private static readonly Dictionary<char, string> symbolsEncodeTable;
- static Strings()
- {
- int len = htmlEntities.Length / 2;
- symbolsDecodeTable = new Dictionary<string, char>(len, StringComparer.Ordinal);
- symbolsEncodeTable = new Dictionary<char, string>(len);
- for (int i = 0; i < len; i++)
- {
- var name = htmlEntities[2 * i];
- var chr = htmlEntities[2 * i + 1][0];
- symbolsDecodeTable.Add(name, chr);
- symbolsEncodeTable.Add(chr, name);
- }
- }
- public static string RandomAlphaNumeric(int length, bool includeNumbers, bool caseSensitive, bool useUnderscore, bool useDash)
- {
- char[] chars = new char[length];
- var rand = new Random();
- for (int i = 0; i < length; i++)
- {
- char newChar = '0';
- bool valid = false;
- while (!valid)
- {
- int charIndex = rand.Next(64);
- if (charIndex <= 9)
- {
- // 0...9 => Nombre [0-9]
- if (includeNumbers)
- {
- valid = true;
- newChar = (char)(charIndex + 48);
- }
- }
- else if (charIndex <= 10 + 25)
- {
- // 10...35 => Lettre majuscule [A-Z] (26 lettres)
- // la lettre A se trouve à l'index 65, la Z à l'index 90
- if (caseSensitive)
- {
- valid = true;
- newChar = (char)(charIndex - 10 + 65);
- }
- }
- else if (charIndex <= 36 + 25)
- {
- // 36...61 => lettre minuscule [a-z] (26 lettres)
- // la lettre a se trouve à l'index 97, la z à l'index 122
- valid = true;
- newChar = (char)(charIndex - 36 + 97);
- }
- else if (charIndex == 62)
- {
- // caractère "_"
- if (useUnderscore)
- {
- valid = true;
- newChar = '_';
- }
- }
- else if (charIndex == 63)
- {
- // caractère "-"
- if (useDash)
- {
- valid = true;
- newChar = '-';
- }
- }
- else
- {
- throw new InvalidOperationException("Erreur dans les intervalles calculés pour la génération de chaîne aléatoire");
- }
- }
- chars[i] = newChar;
- }
- return new string(chars);
- }
- public static string BytesToHexString(byte[] bytes)
- {
- if (bytes == null)
- {
- throw new ArgumentNullException("bytes");
- }
- int length = bytes.Length;
- // Chaîne de résultat : 2 caractères par octet
- char[] result = new char[length * 2];
- for (int i = 0; i < length; i++)
- {
- // Partie gauche de la valeur de l'octet (0 à 15)
- byte digit = (byte)((bytes[i] >> 4) & 0xf);
- // Transformation en caractère hexa de la valeur numérique
- result[i * 2] = (digit > 9) ? (char)(digit + 0x57) : (char)(digit + 0x30);
- // Partie droite de la valeur de l'octet (0 à f)
- digit = (byte)(bytes[i] & 0xf);
- // Transformation en caractère hexa de la valeur numérique
- result[i * 2 + 1] = (digit > 9) ? (char)(digit + 0x57) : (char)(digit + 0x30);
- }
- return new string(result);
- }
- public static byte[] HexStringToBytes(string hexString)
- {
- if (hexString == null)
- return null;
- int length = hexString.Length;
- if (length == 0)
- return new byte[0];
- if (length % 2 == 1)
- {
- // Nombre impair de chiffres : on préfixe par un "0"
- hexString = "0" + hexString;
- length++;
- }
- byte[] bytes = new byte[length / 2];
- for (int i = 0; i < length / 2; i++)
- {
- // Transformation des 2 caractères en sa valeur en octets
- byte b;
- if (!byte.TryParse(hexString.Substring(i * 2, 2), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out b))
- {
- // Echec de la transformation, depuis la chaîne hexa
- return null;
- }
- bytes[i] = b;
- }
- return bytes;
- }
- public static string RemoveDiacritics(string text)
- {
- if (text == null)
- {
- return null;
- }
- var normalizedString = text.Normalize(NormalizationForm.FormD);
- var stringBuilder = new StringBuilder(text.Length);
- for (int i = 0; i < normalizedString.Length; i++)
- {
- char c = normalizedString[i];
- if (CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark)
- {
- stringBuilder.Append(c);
- }
- }
- return stringBuilder.ToString();
- }
- public static string UrlEncode(string text)
- {
- // Sytem.Uri provides reliable parsing
- return Uri.EscapeDataString(text);
- }
- public static string UrlDecode(string text)
- {
- // pre-process for + sign space formatting since System.Uri doesn't handle it
- // plus literals are encoded as %2b normally so this should be safe
- text = text.Replace('+', ' ');
- return Uri.UnescapeDataString(text);
- }
- public static string XmlEncode(string text)
- {
- if (text == null)
- {
- return null;
- }
- return System.Security.SecurityElement.Escape(text);
- }
- public static string HtmlEncode(string text)
- {
- return HtmlEncode(text, false);
- }
- public static string HtmlEncode(string text, bool useNamedEntities)
- {
- if (text == null)
- {
- return null;
- }
- StringBuilder sb = new StringBuilder(text.Length);
- int len = text.Length;
- for (int i = 0; i < len; i++)
- {
- var c = text[i];
- string entity;
- if (c == '<')
- {
- sb.Append("<");
- }
- else if (c == '>')
- {
- sb.Append(">");
- }
- else if (c == '"')
- {
- sb.Append(""");
- }
- else if (c == '&')
- {
- sb.Append("&");
- }
- else if (useNamedEntities && symbolsEncodeTable.TryGetValue(c, out entity))
- {
- // Named entity
- sb.Append('&');
- sb.Append(entity);
- sb.Append(';');
- }
- else if (c > 159)
- {
- // Numeric entity
- sb.Append("&#");
- sb.Append((int)c);
- sb.Append(';');
- }
- else
- {
- sb.Append(text[i]);
- }
- }
- return sb.ToString();
- }
- public static string HtmlDecode(string text)
- {
- if (string.IsNullOrEmpty(text))
- return text;
- return Regex.Replace(text, "\\&([a-zA-Z]{3,6}|#[xX][0-9]{2,4});", DecodeHtmlEntities);
- }
- public static string LimitLeft(string text, int maxlength, string padRight = null)
- {
- if (text == null)
- return null;
- var len = text.Length;
- if (padRight != null)
- maxlength -= padRight.Length;
- if (len <= maxlength)
- return text;
- if (padRight != null)
- return text.Substring(0, maxlength) + padRight;
- return text.Substring(0, maxlength);
- }
- private static string DecodeHtmlEntities(Match match)
- {
- string name = match.Groups[1].Value;
- if (name[0] == '#')
- {
- int val;
- if (name[1] == 'x' || name[1] == 'X')
- {
- // Hexadecimal numeric entity
- val = int.Parse(name.Substring(2), NumberStyles.None | NumberStyles.AllowHexSpecifier);
- }
- else
- {
- // Numeric entity
- val = int.Parse(name.Substring(1), NumberStyles.None);
- }
- return new string((char)val, 1);
- }
- else
- {
- char replace;
- if (!symbolsDecodeTable.TryGetValue(name, out replace))
- {
- return match.Value;
- }
- return new string(replace, 1);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement