Advertisement
styx31

Strings

Apr 25th, 2011
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 17.26 KB | None | 0 0
  1. namespace Coldwire.Text
  2. {
  3.     using System;
  4.     using System.Collections.Generic;
  5.     using System.Globalization;
  6.     using System.Text;
  7.     using System.Text.RegularExpressions;
  8.  
  9.     public static class Strings
  10.     {
  11.         #region HtmlEntities
  12.  
  13.         private static readonly string[] htmlEntities = new[] {
  14.             // Reserved (xml) entities
  15.             "quot", "\"",
  16.             "apos", "'",
  17.             "amp", "&",
  18.             "lt", "<",
  19.             "gt", ">",
  20.  
  21.             // ISO-8859-1 entities
  22.             "nbsp", "\u00a0",
  23.             "iexcl", "¡",
  24.             "cent", "¢",
  25.             "pound", "£",
  26.             "curren", "¤",
  27.             "yen", "¥",
  28.             "brvbar", "¦",
  29.             "sect", "§",
  30.             "uml", "¨",
  31.             "copy", "©",
  32.             "ordf", "ª",
  33.             "laquo", "«",
  34.             "not", "¬",
  35.             "shy", "\u00ad",
  36.             "reg", "®",
  37.             "macr", "¯",
  38.             "deg", "°",
  39.             "plusmn", "±",
  40.             "sup2", "²",
  41.             "sup3", "³",
  42.             "acute", "´",
  43.             "micro", "µ",
  44.             "para", "¶",
  45.             "middot", "·",
  46.             "cedil", "¸",
  47.             "sup1", "¹",
  48.             "ordm", "º",
  49.             "raquo", "»",
  50.             "frac14", "¼",
  51.             "frac12", "½",
  52.             "frac34", "¾",
  53.             "iquest", "¿",
  54.             "times", "×",
  55.             "divide", "÷",
  56.             "Agrave", "À",
  57.             "Aacute", "Á",
  58.             "Acirc", "Â",
  59.             "Atilde", "Ã",
  60.             "Auml", "Ä",
  61.             "Aring", "Å",
  62.             "AElig", "Æ",
  63.             "Ccedil", "Ç",
  64.             "Egrave", "È",
  65.             "Eacute", "É",
  66.             "Ecirc", "Ê",
  67.             "Euml", "Ë",
  68.             "Igrave", "Ì",
  69.             "Iacute", "Í",
  70.             "Icirc", "Î",
  71.             "Iuml", "Ï",
  72.             "ETH", "Ð",
  73.             "Ntilde", "Ñ",
  74.             "Ograve", "Ò",
  75.             "Oacute", "Ó",
  76.             "Ocirc", "Ô",
  77.             "Otilde", "Õ",
  78.             "Ouml", "Ö",
  79.             "Oslash", "Ø",
  80.             "Ugrave", "Ù",
  81.             "Uacute", "Ú",
  82.             "Ucirc", "Û",
  83.             "Uuml", "Ü",
  84.             "Yacute", "Ý",
  85.             "THORN", "Þ",
  86.             "szlig", "ß",
  87.             "agrave", "à",
  88.             "aacute", "á",
  89.             "acirc", "â",
  90.             "atilde", "ã",
  91.             "auml", "ä",
  92.             "aring", "å",
  93.             "aelig", "æ",
  94.             "ccedil", "ç",
  95.             "egrave", "è",
  96.             "eacute", "é",
  97.             "ecirc", "ê",
  98.             "euml", "ë",
  99.             "igrave", "ì",
  100.             "iacute", "í",
  101.             "icirc", "î",
  102.             "iuml", "ï",
  103.             "eth", "ð",
  104.             "ntilde", "ñ",
  105.             "ograve", "ò",
  106.             "oacute", "ó",
  107.             "ocirc", "ô",
  108.             "otilde", "õ",
  109.             "ouml", "ö",
  110.             "oslash", "ø",
  111.             "ugrave", "ù",
  112.             "uacute", "ú",
  113.             "ucirc", "û",
  114.             "uuml", "ü",
  115.             "yacute", "ý",
  116.             "thorn", "þ",
  117.             "yuml", "ÿ",
  118.  
  119.             // Math symbols
  120.             "forall", "∀",
  121.             "part", "∂",
  122.             "exist", "∃",
  123.             "empty", "∅",
  124.             "nabla", "∇",
  125.             "isin", "∈",
  126.             "notin", "∉",
  127.             "ni", "∋",
  128.             "prod", "∏",
  129.             "sum", "∑",
  130.             "minus", "−",
  131.             "lowast", "∗",
  132.             "radic", "√",
  133.             "prop", "∝",
  134.             "infin", "∞",
  135.             "ang", "∠",
  136.             "and", "∧",
  137.             "or", "∨",
  138.             "cap", "∩",
  139.             "cup", "∪",
  140.             "int", "∫",
  141.             "there4", "∴",
  142.             "sim", "∼",
  143.             "cong", "≅",
  144.             "asymp", "≈",
  145.             "ne", "≠",
  146.             "equiv", "≡",
  147.             "le", "≤",
  148.             "ge", "≥",
  149.             "sub", "⊂",
  150.             "sup", "⊃",
  151.             "nsub", "⊄",
  152.             "sube", "⊆",
  153.             "supe", "⊇",
  154.             "oplus", "⊕",
  155.             "otimes", "⊗",
  156.             "perp", "⊥",
  157.             "sdot", "⋅",
  158.  
  159.             // Greek letters
  160.             "Alpha", "Α",
  161.             "Beta", "Β",
  162.             "Gamma", "Γ",
  163.             "Delta", "Δ",
  164.             "Epsilon", "Ε",
  165.             "Zeta", "Ζ",
  166.             "Eta", "Η",
  167.             "Theta", "Θ",
  168.             "Iota", "Ι",
  169.             "Kappa", "Κ",
  170.             "Lambda", "Λ",
  171.             "Mu", "Μ",
  172.             "Nu", "Ν",
  173.             "Xi", "Ξ",
  174.             "Omicron", "Ο",
  175.             "Pi", "Π",
  176.             "Rho", "Ρ",
  177.             "Sigma", "Σ",
  178.             "Tau", "Τ",
  179.             "Upsilon", "Υ",
  180.             "Phi", "Φ",
  181.             "Chi", "Χ",
  182.             "Psi", "Ψ",
  183.             "Omega", "Ω",
  184.             "alpha", "α",
  185.             "beta", "β",
  186.             "gamma", "γ",
  187.             "delta", "δ",
  188.             "epsilon", "ε",
  189.             "zeta", "ζ",
  190.             "eta", "η",
  191.             "theta", "θ",
  192.             "iota", "ι",
  193.             "kappa", "κ",
  194.             "lambda", "λ",
  195.             "mu", "μ",
  196.             "nu", "ν",
  197.             "xi", "ξ",
  198.             "omicron", "ο",
  199.             "pi", "π",
  200.             "rho", "ρ",
  201.             "sigmaf", "ς",
  202.             "sigma", "σ",
  203.             "tau", "τ",
  204.             "upsilon", "υ",
  205.             "phi", "φ",
  206.             "chi", "χ",
  207.             "psi", "ψ",
  208.             "omega", "ω",
  209.             "thetasym", "ϑ",
  210.             "upsih", "ϒ",
  211.             "piv", "ϖ",
  212.  
  213.             // Other entities
  214.             "OElig", "Œ",
  215.             "oelig", "œ",
  216.             "Scaron", "Š",
  217.             "scaron", "š",
  218.             "Yuml", "Ÿ",
  219.             "fnof", "ƒ",
  220.             "circ", "ˆ",
  221.             "tilde", "˜",
  222.             "ensp", "\u2002",
  223.             "emsp", "\u2003",
  224.             "thinsp", "\u2009",
  225.             "zwnj", "\u200c‌",
  226.             "zwj", "‍\u200d",
  227.             "lrm", "‎\u200e",
  228.             "rlm", "‏\u200f",
  229.             "ndash", "–",
  230.             "mdash", "—",
  231.             "lsquo", "‘",
  232.             "rsquo", "’",
  233.             "sbquo", "‚",
  234.             "ldquo", "“",
  235.             "rdquo", "”",
  236.             "bdquo", "„",
  237.             "dagger", "†",
  238.             "Dagger", "‡",
  239.             "bull", "•",
  240.             "hellip", "…",
  241.             "permil", "‰",
  242.             "prime", "′",
  243.             "Prime", "″",
  244.             "lsaquo", "‹",
  245.             "rsaquo", "›",
  246.             "oline", "‾",
  247.             "euro", "€",
  248.             "trade", "™",
  249.             "larr", "←",
  250.             "uarr", "↑",
  251.             "rarr", "→",
  252.             "darr", "↓",
  253.             "harr", "↔",
  254.             "crarr", "↵",
  255.             "lceil", "⌈",
  256.             "rceil", "⌉",
  257.             "lfloor", "⌊",
  258.             "rfloor", "⌋",
  259.             "loz", "◊",
  260.             "spades", "♠",
  261.             "clubs", "♣",
  262.             "hearts", "♥",
  263.             "diams", "♦",
  264.         };
  265.  
  266.         #endregion
  267.  
  268.         private static readonly Dictionary<string, char> symbolsDecodeTable;
  269.  
  270.         private static readonly Dictionary<char, string> symbolsEncodeTable;
  271.  
  272.         static Strings()
  273.         {
  274.             int len = htmlEntities.Length / 2;
  275.  
  276.             symbolsDecodeTable = new Dictionary<string, char>(len, StringComparer.Ordinal);
  277.             symbolsEncodeTable = new Dictionary<char, string>(len);
  278.  
  279.             for (int i = 0; i < len; i++)
  280.             {
  281.                 var name = htmlEntities[2 * i];
  282.                 var chr = htmlEntities[2 * i + 1][0];
  283.  
  284.                 symbolsDecodeTable.Add(name, chr);
  285.                 symbolsEncodeTable.Add(chr, name);
  286.             }
  287.         }
  288.  
  289.         public static string RandomAlphaNumeric(int length, bool includeNumbers, bool caseSensitive, bool useUnderscore, bool useDash)
  290.         {
  291.             char[] chars = new char[length];
  292.  
  293.             var rand = new Random();
  294.  
  295.             for (int i = 0; i < length; i++)
  296.             {
  297.                 char newChar = '0';
  298.                 bool valid = false;
  299.  
  300.                 while (!valid)
  301.                 {
  302.                     int charIndex = rand.Next(64);
  303.  
  304.                     if (charIndex <= 9)
  305.                     {
  306.                         // 0...9 => Nombre [0-9]
  307.                         if (includeNumbers)
  308.                         {
  309.                             valid = true;
  310.                             newChar = (char)(charIndex + 48);
  311.                         }
  312.                     }
  313.                     else if (charIndex <= 10 + 25)
  314.                     {
  315.                         // 10...35 => Lettre majuscule [A-Z] (26 lettres)
  316.                         // la lettre A se trouve à l'index 65, la Z à l'index 90
  317.                         if (caseSensitive)
  318.                         {
  319.                             valid = true;
  320.                             newChar = (char)(charIndex - 10 + 65);
  321.                         }
  322.                     }
  323.                     else if (charIndex <= 36 + 25)
  324.                     {
  325.                         // 36...61 => lettre minuscule [a-z] (26 lettres)
  326.                         // la lettre a se trouve à l'index 97, la z à l'index 122
  327.                         valid = true;
  328.                         newChar = (char)(charIndex - 36 + 97);
  329.                     }
  330.                     else if (charIndex == 62)
  331.                     {
  332.                         // caractère "_"
  333.                         if (useUnderscore)
  334.                         {
  335.                             valid = true;
  336.                             newChar = '_';
  337.                         }
  338.                     }
  339.                     else if (charIndex == 63)
  340.                     {
  341.                         // caractère "-"
  342.                         if (useDash)
  343.                         {
  344.                             valid = true;
  345.                             newChar = '-';
  346.                         }
  347.                     }
  348.                     else
  349.                     {
  350.                         throw new InvalidOperationException("Erreur dans les intervalles calculés pour la génération de chaîne aléatoire");
  351.                     }
  352.                 }
  353.  
  354.                 chars[i] = newChar;
  355.             }
  356.  
  357.             return new string(chars);
  358.         }
  359.  
  360.         public static string BytesToHexString(byte[] bytes)
  361.         {
  362.             if (bytes == null)
  363.             {
  364.                 throw new ArgumentNullException("bytes");
  365.             }
  366.  
  367.             int length = bytes.Length;
  368.  
  369.             // Chaîne de résultat : 2 caractères par octet
  370.             char[] result = new char[length * 2];
  371.  
  372.             for (int i = 0; i < length; i++)
  373.             {
  374.                 // Partie gauche de la valeur de l'octet (0 à 15)
  375.                 byte digit = (byte)((bytes[i] >> 4) & 0xf);
  376.  
  377.                 // Transformation en caractère hexa de la valeur numérique
  378.                 result[i * 2] = (digit > 9) ? (char)(digit + 0x57) : (char)(digit + 0x30);
  379.  
  380.                 // Partie droite de la valeur de l'octet (0 à f)
  381.                 digit = (byte)(bytes[i] & 0xf);
  382.  
  383.                 // Transformation en caractère hexa de la valeur numérique
  384.                 result[i * 2 + 1] = (digit > 9) ? (char)(digit + 0x57) : (char)(digit + 0x30);
  385.             }
  386.  
  387.             return new string(result);
  388.         }
  389.  
  390.         public static byte[] HexStringToBytes(string hexString)
  391.         {
  392.             if (hexString == null)
  393.                 return null;
  394.  
  395.             int length = hexString.Length;
  396.  
  397.             if (length == 0)
  398.                 return new byte[0];
  399.  
  400.             if (length % 2 == 1)
  401.             {
  402.                 // Nombre impair de chiffres : on préfixe par un "0"
  403.                 hexString = "0" + hexString;
  404.                 length++;
  405.             }
  406.  
  407.             byte[] bytes = new byte[length / 2];
  408.  
  409.             for (int i = 0; i < length / 2; i++)
  410.             {
  411.                 // Transformation des 2 caractères en sa valeur en octets
  412.                 byte b;
  413.  
  414.                 if (!byte.TryParse(hexString.Substring(i * 2, 2), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out b))
  415.                 {
  416.                     // Echec de la transformation, depuis la chaîne hexa
  417.                     return null;
  418.                 }
  419.  
  420.                 bytes[i] = b;
  421.             }
  422.  
  423.             return bytes;
  424.         }
  425.  
  426.         public static string RemoveDiacritics(string text)
  427.         {
  428.             if (text == null)
  429.             {
  430.                 return null;
  431.             }
  432.  
  433.             var normalizedString = text.Normalize(NormalizationForm.FormD);
  434.  
  435.             var stringBuilder = new StringBuilder(text.Length);
  436.  
  437.             for (int i = 0; i < normalizedString.Length; i++)
  438.             {
  439.                 char c = normalizedString[i];
  440.                 if (CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark)
  441.                 {
  442.                     stringBuilder.Append(c);
  443.                 }
  444.             }
  445.  
  446.             return stringBuilder.ToString();
  447.         }
  448.  
  449.         public static string UrlEncode(string text)
  450.         {
  451.             // Sytem.Uri provides reliable parsing
  452.             return Uri.EscapeDataString(text);
  453.         }
  454.  
  455.         public static string UrlDecode(string text)
  456.         {
  457.             // pre-process for + sign space formatting since System.Uri doesn't handle it
  458.             // plus literals are encoded as %2b normally so this should be safe
  459.             text = text.Replace('+', ' ');
  460.             return Uri.UnescapeDataString(text);
  461.         }
  462.  
  463.         public static string XmlEncode(string text)
  464.         {
  465.             if (text == null)
  466.             {
  467.                 return null;
  468.             }
  469.  
  470.             return System.Security.SecurityElement.Escape(text);
  471.         }
  472.  
  473.         public static string HtmlEncode(string text)
  474.         {
  475.             return HtmlEncode(text, false);
  476.         }
  477.  
  478.         public static string HtmlEncode(string text, bool useNamedEntities)
  479.         {
  480.             if (text == null)
  481.             {
  482.                 return null;
  483.             }
  484.  
  485.             StringBuilder sb = new StringBuilder(text.Length);
  486.  
  487.             int len = text.Length;
  488.  
  489.             for (int i = 0; i < len; i++)
  490.             {
  491.                 var c = text[i];
  492.  
  493.                 string entity;
  494.  
  495.                 if (c == '<')
  496.                 {
  497.                     sb.Append("&lt;");
  498.                 }
  499.                 else if (c == '>')
  500.                 {
  501.                     sb.Append("&gt;");
  502.                 }
  503.                 else if (c == '"')
  504.                 {
  505.                     sb.Append("&quot;");
  506.                 }
  507.                 else if (c == '&')
  508.                 {
  509.                     sb.Append("&amp;");
  510.                 }
  511.                 else if (useNamedEntities && symbolsEncodeTable.TryGetValue(c, out entity))
  512.                 {
  513.                     // Named entity
  514.                     sb.Append('&');
  515.                     sb.Append(entity);
  516.                     sb.Append(';');
  517.                 }
  518.                 else if (c > 159)
  519.                 {
  520.                     // Numeric entity
  521.                     sb.Append("&#");
  522.                     sb.Append((int)c);
  523.                     sb.Append(';');
  524.                 }
  525.                 else
  526.                 {
  527.                     sb.Append(text[i]);
  528.                 }
  529.             }
  530.  
  531.             return sb.ToString();
  532.         }
  533.  
  534.  
  535.         public static string HtmlDecode(string text)
  536.         {
  537.             if (string.IsNullOrEmpty(text))
  538.                 return text;
  539.  
  540.             return Regex.Replace(text, "\\&([a-zA-Z]{3,6}|#[xX][0-9]{2,4});", DecodeHtmlEntities);
  541.         }
  542.  
  543.         public static string LimitLeft(string text, int maxlength, string padRight = null)
  544.         {
  545.             if (text == null)
  546.                 return null;
  547.  
  548.             var len = text.Length;
  549.  
  550.             if (padRight != null)
  551.                 maxlength -= padRight.Length;
  552.  
  553.             if (len <= maxlength)
  554.                 return text;
  555.  
  556.             if (padRight != null)
  557.                 return text.Substring(0, maxlength) + padRight;
  558.  
  559.             return text.Substring(0, maxlength);
  560.         }
  561.  
  562.         private static string DecodeHtmlEntities(Match match)
  563.         {
  564.             string name = match.Groups[1].Value;
  565.  
  566.             if (name[0] == '#')
  567.             {
  568.                 int val;
  569.  
  570.                 if (name[1] == 'x' || name[1] == 'X')
  571.                 {
  572.                     // Hexadecimal numeric entity
  573.                     val = int.Parse(name.Substring(2), NumberStyles.None | NumberStyles.AllowHexSpecifier);
  574.                 }
  575.                 else
  576.                 {
  577.                     // Numeric entity
  578.                     val = int.Parse(name.Substring(1), NumberStyles.None);
  579.                 }
  580.  
  581.                 return new string((char)val, 1);
  582.             }
  583.             else
  584.             {
  585.                 char replace;
  586.  
  587.                 if (!symbolsDecodeTable.TryGetValue(name, out replace))
  588.                 {
  589.                     return match.Value;
  590.                 }
  591.  
  592.                 return new string(replace, 1);
  593.             }
  594.         }
  595.     }
  596. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement