andrew4582

StringUtils

Aug 15th, 2010
215
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 10.17 KB | None | 0 0
  1.  
  2.  
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.Text;
  7. using System.Text.RegularExpressions;
  8. using System.Linq;
  9. using System.Globalization;
  10.  
  11. namespace System.Utilities
  12. {
  13.   internal static class StringUtils
  14.   {
  15.     public const string CarriageReturnLineFeed = "\r\n";
  16.     public const string Empty = "";
  17.     public const char CarriageReturn = '\r';
  18.     public const char LineFeed = '\n';
  19.     public const char Tab = '\t';
  20.  
  21.     //public static string FormatWith(this string format, params object[] args)
  22.     //{
  23.     //  return FormatWith(format, null, args);
  24.     //}
  25.  
  26.     public static string FormatWith(this string format, IFormatProvider provider, params object[] args)
  27.     {
  28.       ValidationUtils.ArgumentNotNull(format, "format");
  29.  
  30.       return string.Format(provider, format, args);
  31.     }
  32.  
  33.     /// <summary>
  34.     /// Determines whether the string contains white space.
  35.     /// </summary>
  36.     /// <param name="s">The string to test for white space.</param>
  37.     /// <returns>
  38.     ///     <c>true</c> if the string contains white space; otherwise, <c>false</c>.
  39.     /// </returns>
  40.     public static bool ContainsWhiteSpace(string s)
  41.     {
  42.       if (s == null)
  43.         throw new ArgumentNullException("s");
  44.  
  45.       for (int i = 0; i < s.Length; i++)
  46.       {
  47.         if (char.IsWhiteSpace(s[i]))
  48.           return true;
  49.       }
  50.       return false;
  51.     }
  52.  
  53.     /// <summary>
  54.     /// Determines whether the string is all white space. Empty string will return false.
  55.     /// </summary>
  56.     /// <param name="s">The string to test whether it is all white space.</param>
  57.     /// <returns>
  58.     ///     <c>true</c> if the string is all white space; otherwise, <c>false</c>.
  59.     /// </returns>
  60.     public static bool IsWhiteSpace(string s)
  61.     {
  62.       if (s == null)
  63.         throw new ArgumentNullException("s");
  64.  
  65.       if (s.Length == 0)
  66.         return false;
  67.  
  68.       for (int i = 0; i < s.Length; i++)
  69.       {
  70.         if (!char.IsWhiteSpace(s[i]))
  71.           return false;
  72.       }
  73.  
  74.       return true;
  75.     }
  76.  
  77.     /// <summary>
  78.     /// Ensures the target string ends with the specified string.
  79.     /// </summary>
  80.     /// <param name="target">The target.</param>
  81.     /// <param name="value">The value.</param>
  82.     /// <returns>The target string with the value string at the end.</returns>
  83.     public static string EnsureEndsWith(string target, string value)
  84.     {
  85.       if (target == null)
  86.         throw new ArgumentNullException("target");
  87.  
  88.       if (value == null)
  89.         throw new ArgumentNullException("value");
  90.  
  91.       if (target.Length >= value.Length)
  92.       {
  93.         if (string.Compare(target, target.Length - value.Length, value, 0, value.Length, StringComparison.OrdinalIgnoreCase) ==
  94.                         0)
  95.           return target;
  96.  
  97.         string trimmedString = target.TrimEnd(null);
  98.  
  99.         if (string.Compare(trimmedString, trimmedString.Length - value.Length, value, 0, value.Length,
  100.                         StringComparison.OrdinalIgnoreCase) == 0)
  101.           return target;
  102.       }
  103.  
  104.       return target + value;
  105.     }
  106.  
  107.     public static bool IsNullOrEmptyOrWhiteSpace(string s)
  108.     {
  109.       if (string.IsNullOrEmpty(s))
  110.         return true;
  111.       else if (IsWhiteSpace(s))
  112.         return true;
  113.       else
  114.         return false;
  115.     }
  116.  
  117.     /// <summary>
  118.     /// Perform an action if the string is not null or empty.
  119.     /// </summary>
  120.     /// <param name="value">The value.</param>
  121.     /// <param name="action">The action to perform.</param>
  122.     public static void IfNotNullOrEmpty(string value, Action<string> action)
  123.     {
  124.       IfNotNullOrEmpty(value, action, null);
  125.     }
  126.  
  127.     private static void IfNotNullOrEmpty(string value, Action<string> trueAction, Action<string> falseAction)
  128.     {
  129.       if (!string.IsNullOrEmpty(value))
  130.       {
  131.         if (trueAction != null)
  132.           trueAction(value);
  133.       }
  134.       else
  135.       {
  136.         if (falseAction != null)
  137.           falseAction(value);
  138.       }
  139.     }
  140.  
  141.     /// <summary>
  142.     /// Indents the specified string.
  143.     /// </summary>
  144.     /// <param name="s">The string to indent.</param>
  145.     /// <param name="indentation">The number of characters to indent by.</param>
  146.     /// <returns></returns>
  147.     public static string Indent(string s, int indentation)
  148.     {
  149.       return Indent(s, indentation, ' ');
  150.     }
  151.  
  152.     /// <summary>
  153.     /// Indents the specified string.
  154.     /// </summary>
  155.     /// <param name="s">The string to indent.</param>
  156.     /// <param name="indentation">The number of characters to indent by.</param>
  157.     /// <param name="indentChar">The indent character.</param>
  158.     /// <returns></returns>
  159.     public static string Indent(string s, int indentation, char indentChar)
  160.     {
  161.       if (s == null)
  162.         throw new ArgumentNullException("s");
  163.  
  164.       if (indentation <= 0)
  165.         throw new ArgumentException("Must be greater than zero.", "indentation");
  166.  
  167.       StringReader sr = new StringReader(s);
  168.       StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
  169.  
  170.       ActionTextReaderLine(sr, sw, delegate(TextWriter tw, string line)
  171.       {
  172.         tw.Write(new string(indentChar, indentation));
  173.         tw.Write(line);
  174.       });
  175.  
  176.       return sw.ToString();
  177.     }
  178.  
  179.     private delegate void ActionLine(TextWriter textWriter, string line);
  180.  
  181.     private static void ActionTextReaderLine(TextReader textReader, TextWriter textWriter, ActionLine lineAction)
  182.     {
  183.       string line;
  184.       bool firstLine = true;
  185.       while ((line = textReader.ReadLine()) != null)
  186.       {
  187.         if (!firstLine)
  188.           textWriter.WriteLine();
  189.         else
  190.           firstLine = false;
  191.  
  192.         lineAction(textWriter, line);
  193.       }
  194.     }
  195.  
  196.     /// <summary>
  197.     /// Numbers the lines.
  198.     /// </summary>
  199.     /// <param name="s">The string to number.</param>
  200.     /// <returns></returns>
  201.     public static string NumberLines(string s)
  202.     {
  203.       if (s == null)
  204.         throw new ArgumentNullException("s");
  205.  
  206.       StringReader sr = new StringReader(s);
  207.       StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
  208.  
  209.       int lineNumber = 1;
  210.  
  211.       ActionTextReaderLine(sr, sw, delegate(TextWriter tw, string line)
  212.       {
  213.         tw.Write(lineNumber.ToString(CultureInfo.InvariantCulture).PadLeft(4));
  214.         tw.Write(". ");
  215.         tw.Write(line);
  216.  
  217.         lineNumber++;
  218.       });
  219.  
  220.       return sw.ToString();
  221.     }
  222.  
  223.     /// <summary>
  224.     /// Nulls an empty string.
  225.     /// </summary>
  226.     /// <param name="s">The string.</param>
  227.     /// <returns>Null if the string was null, otherwise the string unchanged.</returns>
  228.     public static string NullEmptyString(string s)
  229.     {
  230.       return (string.IsNullOrEmpty(s)) ? null : s;
  231.     }
  232.  
  233.     public static string ReplaceNewLines(string s, string replacement)
  234.     {
  235.       StringReader sr = new StringReader(s);
  236.       StringBuilder sb = new StringBuilder();
  237.  
  238.       bool first = true;
  239.  
  240.       string line;
  241.       while ((line = sr.ReadLine()) != null)
  242.       {
  243.         if (first)
  244.           first = false;
  245.         else
  246.           sb.Append(replacement);
  247.  
  248.         sb.Append(line);
  249.       }
  250.  
  251.       return sb.ToString();
  252.     }
  253.  
  254.     public static string Truncate(string s, int maximumLength)
  255.     {
  256.       return Truncate(s, maximumLength, "...");
  257.     }
  258.  
  259.     public static string Truncate(string s, int maximumLength, string suffix)
  260.     {
  261.       if (suffix == null)
  262.         throw new ArgumentNullException("suffix");
  263.  
  264.       if (maximumLength <= 0)
  265.         throw new ArgumentException("Maximum length must be greater than zero.", "maximumLength");
  266.  
  267.       int subStringLength = maximumLength - suffix.Length;
  268.  
  269.       if (subStringLength <= 0)
  270.         throw new ArgumentException("Length of suffix string is greater or equal to maximumLength");
  271.  
  272.       if (s != null && s.Length > maximumLength)
  273.       {
  274.         string truncatedString = s.Substring(0, subStringLength);
  275.         // incase the last character is a space
  276.         truncatedString = truncatedString.Trim();
  277.         truncatedString += suffix;
  278.  
  279.         return truncatedString;
  280.       }
  281.       else
  282.       {
  283.         return s;
  284.       }
  285.     }
  286.  
  287.     public static StringWriter CreateStringWriter(int capacity)
  288.     {
  289.       StringBuilder sb = new StringBuilder(capacity);
  290.       StringWriter sw = new StringWriter(sb, CultureInfo.InvariantCulture);
  291.  
  292.       return sw;
  293.     }
  294.  
  295.     public static int? GetLength(string value)
  296.     {
  297.       if (value == null)
  298.         return null;
  299.       else
  300.         return value.Length;
  301.     }
  302.  
  303.     public static string ToCharAsUnicode(char c)
  304.     {
  305.       using (StringWriter w = new StringWriter(CultureInfo.InvariantCulture))
  306.       {
  307.         WriteCharAsUnicode(w, c);
  308.         return w.ToString();
  309.       }
  310.     }
  311.  
  312.     public static void WriteCharAsUnicode(TextWriter writer, char c)
  313.     {
  314.       ValidationUtils.ArgumentNotNull(writer, "writer");
  315.  
  316.       char h1 = MathUtils.IntToHex((c >> 12) & '\x000f');
  317.       char h2 = MathUtils.IntToHex((c >> 8) & '\x000f');
  318.       char h3 = MathUtils.IntToHex((c >> 4) & '\x000f');
  319.       char h4 = MathUtils.IntToHex(c & '\x000f');
  320.  
  321.       writer.Write('\\');
  322.       writer.Write('u');
  323.       writer.Write(h1);
  324.       writer.Write(h2);
  325.       writer.Write(h3);
  326.       writer.Write(h4);
  327.     }
  328.  
  329.     public static TSource ForgivingCaseSensitiveFind<TSource>(this IEnumerable<TSource> source, Func<TSource, string> valueSelector, string testValue)
  330.     {
  331.       if (source == null)
  332.         throw new ArgumentNullException("source");
  333.       if (valueSelector == null)
  334.         throw new ArgumentNullException("valueSelector");
  335.  
  336.       var caseInsensitiveResults = source.Where(s => string.Compare(valueSelector(s), testValue, StringComparison.OrdinalIgnoreCase) == 0);
  337.       if (caseInsensitiveResults.Count() <= 1)
  338.       {
  339.         return caseInsensitiveResults.SingleOrDefault();
  340.       }
  341.       else
  342.       {
  343.         // multiple results returned. now filter using case sensitivity
  344.         var caseSensitiveResults = source.Where(s => string.Compare(valueSelector(s), testValue, StringComparison.Ordinal) == 0);
  345.         return caseSensitiveResults.SingleOrDefault();
  346.       }
  347.     }
  348.   }
  349. }
Advertisement
Add Comment
Please, Sign In to add comment