andrew4582

StringHelper

Aug 4th, 2010
281
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 21.11 KB | None | 0 0
  1.  using System;
  2.  using System.Collections.Generic;
  3.  using System.Text;
  4.  using System.Text.RegularExpressions;
  5.  using System.Web;
  6.  
  7.  namespace  BA.Core {
  8.      using System.Linq;
  9.  
  10.      public  static  class  StringHelper  {
  11.          /// <summary>
  12.          /// "4000"
  13.          /// </summary>
  14.          public  const  int  MAX_NVARCHAR_LENGTH = 4000;
  15.  
  16.          public  static  string  HtmlDecode(string  s) {
  17.              return  HttpUtility .HtmlDecode(s);
  18.          }
  19.          public  static  string  HtmlEncode(string  s) {
  20.              return  HttpUtility .HtmlEncode(s);
  21.          }
  22.          public  static  string  UrlDecode(string  s) {
  23.              return  HttpUtility .UrlDecode(s);
  24.          }
  25.          public  static  string  UrlEncode(string  s) {
  26.              return  HttpUtility .UrlEncode(s);
  27.          }
  28.          public  static  string [] SplitNewLines(string  s) {
  29.              return  s.Split(Environment .NewLine.ToCharArray(),StringSplitOptions .RemoveEmptyEntries);
  30.          }
  31.          public  static  string [] SplitRemoveEmptyEntries(string  s,string  separator) {
  32.              if (separator.IsNullOrEmptyTrim())
  33.                  return  new  string [] { };
  34.              return  s.Split(separator.ToCharArray(),StringSplitOptions .RemoveEmptyEntries);
  35.          }
  36.          public  static  string  ToBase64String(string  s) {
  37.              if (s == null )
  38.                  return  null ;
  39.              if (s.IsNullOrEmptyTrim() == true )
  40.                  return  s;
  41.              return  Convert .ToBase64String(ASCIIEncoding .Unicode.GetBytes(s));
  42.          }
  43.          public  static  string  FromBase64String(string  s) {
  44.              if (s == null )
  45.                  return  null ;
  46.              if (s.IsNullOrEmptyTrim())
  47.                  return  s;
  48.              return  ASCIIEncoding .Unicode.GetString(Convert .FromBase64String(s));
  49.          }
  50.          public  static  bool  IsNull(string  s) {
  51.              return  IsNullOrEmptyTrim(s);
  52.          }
  53.          public  static  bool  IsNullOrEmptyTrim(string  s) {
  54.              if (s == null )
  55.                  return  true ;
  56.              if (string .IsNullOrEmpty(s))
  57.                  return  true ;
  58.              if (s.Equals(Environment .NewLine))
  59.                  return  false ;
  60.              if (string .IsNullOrEmpty(s.Trim()))
  61.                  return  true ;
  62.              return  false ;
  63.          }
  64.          public  static  bool  IsNullOrEmptyTrim(string  s,params  char [] trimChars) {
  65.              if (s == null )
  66.                  return  true ;
  67.              if (string .IsNullOrEmpty(s))
  68.                  return  true ;
  69.              if (string .IsNullOrEmpty(s.Trim(trimChars)))
  70.                  return  true ;
  71.              return  false ;
  72.          }
  73.          public  static  string  ParseTitleString(string  s) {
  74.              if (s == null )
  75.                  return  null ;
  76.              string  result = "" ;
  77.              for (int  i = 0;i < s.Length;i++) {
  78.                  char  c = s[i];
  79.                  if (char .IsUpper(c)) {
  80.                      if (i != 0) {
  81.                          int  h = i - 1;
  82.                          if (h > -1) {
  83.                              char  p = s[h];
  84.                              if (char .IsUpper(p)) {
  85.                                  result += c.ToString();
  86.                                  continue ;
  87.                              }
  88.                          }
  89.                          result += " " ;
  90.                      }
  91.                  }
  92.                  result += c.ToString();
  93.              }
  94.              return  result;
  95.          }
  96.          public  static  string  ParseSentenceString(string  s) {
  97.              if (s == null )
  98.                  return  null ;
  99.              string  result = "" ;
  100.              bool  passfirst = false ;
  101.              for (int  i = 0;i < s.Length;i++) {
  102.                  char  c = s[i];
  103.                  if (!char .IsUpper(c)) {
  104.                      result += c.ToString();
  105.                      continue ;
  106.                  }
  107.  
  108.                  if (!passfirst) {
  109.                      result += " " ;
  110.                      result += c.ToString();
  111.                      passfirst = true ;
  112.                  }
  113.                  else  {
  114.                      int  h = i - 1;
  115.                      int  j = i + 1;
  116.                      bool  nextUpper = false ;
  117.                      bool  previousUpper = false ;
  118.  
  119.                      if (h > -1) {
  120.                          char  p = s[h];
  121.                          if (char .IsUpper(p)) {
  122.                              nextUpper = true ;
  123.                          }
  124.                      }
  125.                      if (j < s.Length) {
  126.                          char  n = s[j];
  127.                          if (char .IsUpper(n)) {
  128.                              previousUpper = true ;
  129.                          }
  130.                      }
  131.                      if (nextUpper || previousUpper) {
  132.                          if (previousUpper) {
  133.                              if (!nextUpper)
  134.                                  result += " " ;
  135.                              result += c.ToString();
  136.                          }
  137.                          else  {
  138.                              if (nextUpper && previousUpper)
  139.                                  result += " "  + c.ToString();
  140.                              else  if (nextUpper && !previousUpper)
  141.                                  result += c.ToString();
  142.                              else  if (!nextUpper && previousUpper)
  143.                                  result += c.ToString();
  144.                          }
  145.                      }
  146.                      else
  147.                          result += c.ToString().ToLowerInvariant();
  148.                  }
  149.              }
  150.              return  result;
  151.          }
  152.          public  static  string  Left(string  s,int  length) {
  153.              if (length < 1)
  154.                  return  s;
  155.              if (s.Length < length)
  156.                  return  s;
  157.              return  s.Substring(0,length);
  158.          }
  159.          public  static  string  LeftDbMax(string  s) {
  160.              int  length = MAX_NVARCHAR_LENGTH;
  161.              if (length < 1)
  162.                  return  s;
  163.              if (s.Length < length)
  164.                  return  s;
  165.              return  s.Substring(0,length);
  166.          }
  167.          public  static  string  RemoveSpaces(string  s) {
  168.              if (s == null )
  169.                  return  null ;
  170.              string  result = string .Empty;
  171.              for (int  i = 0;i < s.Length;i++) {
  172.                  char  c = s[i];
  173.                  if (char .IsWhiteSpace(c))
  174.                      continue ;
  175.                  result += c.ToString();
  176.              }
  177.              return  result;
  178.          }
  179.          public  static  string  ReplaceNonAlphaNumeric(string  s) {
  180.              string  build = null ;
  181.              foreach (char  c in  s.ToCharArray()) {
  182.                  if (IsAlphaNumeric(c.ToString()))
  183.                      build += c.ToString();
  184.              }
  185.              return  build;
  186.          }
  187.          public  static  bool  IsNumeric(string  s) {
  188.              if (IsNull(s))
  189.                  return  false ;
  190.  
  191.              decimal  r = 0;
  192.              if (decimal .TryParse(s,out  r))
  193.                  return  true ;
  194.              return  false ;
  195.          }
  196.          // function To test for only Alpha Chars.
  197.          public  static  bool  IsAlpha(string  strToCheck) {
  198.              Regex  objAlphaPattern = new  Regex ("[^a-zA-Z]" );
  199.              return  !objAlphaPattern.IsMatch(strToCheck.Replace(" " ,"" ));
  200.          }
  201.          // function to Check for AlphaNumeric.
  202.          public  static  bool  IsAlphaNumeric(string  strToCheck) {
  203.              Regex  objAlphaNumericPattern = new  Regex ("[^a-zA-Z0-9]" );
  204.              return  !objAlphaNumericPattern.IsMatch(strToCheck.Replace(" " ,"" ));
  205.          }
  206.          public  static  string  Replace(string  s,Dictionary <string ,string > values) {
  207.              StringBuilder  builder = new  StringBuilder (s);
  208.              foreach (string  key in  values.Keys) {
  209.                  builder.Replace(key,values[key]);
  210.              }
  211.              return  builder.ToString();
  212.          }
  213.          public  static  string  Truncate(string  s,int  maximumLength) {
  214.              return  Truncate(s,maximumLength,"..." );
  215.          }
  216.          public  static  string  Truncate(string  s,int  maximumLength,string  suffix) {
  217.              if (suffix == null )
  218.                  throw  new  ArgumentNullException ("suffix" );
  219.              if (maximumLength <= 0)
  220.                  throw  new  ArgumentException ("Maximum length must be greater than zero." ,"maximumLength" );
  221.              int  subStringLength = maximumLength - suffix.Length;
  222.              if (subStringLength <= 0)
  223.                  throw  new  ArgumentException ("Length of suffix string is greater or equal to maximumLength" );
  224.              if (s != null  && s.Length > maximumLength) {
  225.                  string  truncatedString = s.Substring(0,subStringLength);
  226.                  // incase the last character is a space
  227.                  truncatedString = truncatedString.Trim();
  228.                  truncatedString += suffix;
  229.                  return  truncatedString;
  230.              }
  231.              else  {
  232.                  return  s;
  233.              }
  234.          }
  235.          public  static  T ToEnum<T>(string  s) where  T:IComparable ,IFormattable  {
  236.              T defaultValue = default (T);
  237.              return  ToEnum<T>(s,defaultValue);
  238.          }
  239.          public  static  T ToEnum<T>(string  s,T defaultValue) where  T:IComparable ,IFormattable  {
  240.              T convertedValue = defaultValue;
  241.              if (!string .IsNullOrEmpty(s)) {
  242.                  try  {
  243.                      convertedValue = (T)Enum .Parse(typeof (T),s.Trim(),true );
  244.                  }
  245.                  catch (ArgumentException ) {
  246.                      return  defaultValue;
  247.                  }
  248.              }
  249.              return  convertedValue;
  250.          }
  251.          public  static  string  GetPluralName(string  name) {
  252.              int  index = name.IndexOf("Of" ,StringComparison .Ordinal);
  253.              if ((((index > 3) && (index < (name.Length - 4))) && (char .IsLower(name,index - 1) && (name[index - 1] != 's' ))) && char .IsUpper(name,index + 2)) {
  254.                  return  (name.Substring(0,index) + "s"  + name.Substring(index));
  255.              }
  256.              string  str = "" ;
  257.              string  str2 = name.ToLowerInvariant();
  258.              if (str2.EndsWith("created" ,StringComparison .Ordinal) || name.EndsWith("updated" ,StringComparison .Ordinal)) {
  259.                  if (name.Length < 10) {
  260.                      return  name;
  261.                  }
  262.                  string  str3 = str2.Substring(name.Length - 9,2);
  263.                  string  str4 = str2.Substring(name.Length - 10,3);
  264.                  switch (str3) {
  265.                      case  "co" :
  266.                      case  "re" :
  267.                      case  "un" :
  268.                          return  name;
  269.                  }
  270.                  switch (str4) {
  271.                      case  "mis" :
  272.                      case  "pro" :
  273.                          return  name;
  274.                  }
  275.                  str = name.Substring(name.Length - 7);
  276.                  name = name.Substring(0,name.Length - 7);
  277.              }
  278.              str2 = name.ToLowerInvariant();
  279.              if ((((!str2.EndsWith("information" ) && !str2.EndsWith("complete" )) && (!str2.EndsWith("_info" ) && !str2.EndsWith("_data" ))) && (!name.EndsWith("Info" ) && !name.EndsWith("Data" ))) && !name.EndsWith("Staff" )) {
  280.                  if (((str2.EndsWith("x" ) || str2.EndsWith("ch" )) || str2.EndsWith("ss" )) || str2.EndsWith("status" )) {
  281.                      name = name + "es" ;
  282.                  }
  283.                  else  if (!((!str2.EndsWith("y" ) || (str2.Length <= 1)) || IsVowel(str2[str2.Length - 2]))) {
  284.                      name = name.Substring(0,name.Length - 1) + "ies" ;
  285.                  }
  286.                  else  if (!str2.EndsWith("s" )) {
  287.                      name = name + "s" ;
  288.                  }
  289.              }
  290.              string  result = (name + str);
  291.              if (result.EqualsIgnoreCase(name)) {
  292.                  if (result.EndsWith("s" ))
  293.                      result += "es" ;
  294.                  else
  295.                      result += "s" ;
  296.              }
  297.              return  result;
  298.          }
  299.          public  static  bool  IsVowel(char  c) {
  300.              return  "aeiuo" .Contains<char >(char .ToLowerInvariant(c));
  301.          }
  302.          public  static  string  Repeat(string  s,int  num) {
  303.              return  Repeat(s,num,string .Empty);
  304.          }
  305.          public  static  string  Repeat(string  s,int  num,string  delimeter) {
  306.              if (IsNull(s))
  307.                  return  s;
  308.              StringBuilder  sb = new  StringBuilder ();
  309.              for (int  i = 0;i < num;i++) {
  310.                  sb.Append(s);
  311.                  if (delimeter != null )
  312.                      sb.Append(delimeter);
  313.              }
  314.              return  sb.ToString();
  315.          }
  316.          public  static  string  Repeat(string  s,int  num,Func <string ,string > actions) {
  317.              if (actions == null )
  318.                  return  s;
  319.              StringBuilder  sbuilder = new  StringBuilder ();
  320.              for (int  i = 0;i < num;i++) {
  321.                  sbuilder.Append(actions(s));
  322.              }
  323.              return  sbuilder.ToString();
  324.          }
  325.          public  static  string  Repeat(string  s,int  num,Func <string ,int ,string > actions) {
  326.              if (actions == null )
  327.                  return  s;
  328.              StringBuilder  sbuilder = new  StringBuilder ();
  329.              for (int  i = 0;i < num;i++) {
  330.                  sbuilder.Append(actions(s,i));
  331.              }
  332.              return  sbuilder.ToString();
  333.          }
  334.          public  static  string  TrimStart(string  s,string  value) {
  335.              if (IsNull(s))
  336.                  return  s;
  337.              EnsureNotNull(ref  value);
  338.              if (s.Length < value.Length)
  339.                  return  s;
  340.              return  s.Substring(0,value.Length);
  341.          }
  342.          public  static  string  TrimEnd(string  s,string  value) {
  343.              if (IsNull(s))
  344.                  return  s;
  345.              EnsureNotNull(ref  value);
  346.              if (s.Length < value.Length)
  347.                  return  s;
  348.              return  s.Substring(s.Length - value.Length,value.Length);
  349.          }
  350.          public  static  string  Append(string  s,string  value) {
  351.              return  s + EnsureNotNull(value);
  352.          }
  353.          public  static  string  Prepend(string  s,string  value) {
  354.              return  EnsureNotNull(value) + s;
  355.          }
  356.  
  357.          public  static  string  EnsureNotNull(ref  string  s) {
  358.              return  EnsureNotNull(s);
  359.          }
  360.          public  static  string  EnsureNotNull(string  s) {
  361.              if (s == null )
  362.                  return  string .Empty;
  363.              else
  364.                  return  s;
  365.          }
  366.          public  static  string  Wrap(string  s,string  value) {
  367.              EnsureNotNull(ref  s);
  368.              EnsureNotNull(ref  value);
  369.              return  value + s + value;
  370.          }
  371.          public  static  string  WrapInQuotes(string  s) {
  372.              return  Wrap(s,"'" );
  373.          }
  374.          public  static  int  ToInt32(string  s) {
  375.              return  ConvertTo<int >(s);
  376.          }
  377.          public  static  int  ToInt32(string  s,int  defaultValue) {
  378.              return  ConvertTo<int >(s,defaultValue);
  379.          }
  380.          public  static  decimal  ToDecimal(string  s) {
  381.              return  ConvertTo<decimal >(s);
  382.          }
  383.          public  static  decimal  ToDecimal(string  s,decimal  defaultValue) {
  384.              return  ConvertTo<decimal >(s,defaultValue);
  385.          }
  386.          public  static  float  ToFloat(string  s) {
  387.              return  ConvertTo<float >(s);
  388.          }
  389.          public  static  float  ToFloat(string  s,float  defaultValue) {
  390.              return  ConvertTo<float >(s,defaultValue);
  391.          }
  392.          public  static  bool  ToBool(string  s) {
  393.              return  ConvertTo<bool >(s);
  394.          }
  395.          public  static  bool  ToBool(string  s,bool  defaultValue) {
  396.              return  ConvertTo<bool >(s,defaultValue);
  397.          }
  398.          public  static  DateTime ? ToDateTime(string  s) {
  399.              return  ConvertTo<DateTime ?>(s);
  400.          }
  401.          public  static  DateTime ? ToDateTime(string  s,DateTime  defaultValue) {
  402.              return  ConvertTo<DateTime ?>(s,defaultValue);
  403.          }
  404.          public  static  T ConvertTo<T>(string  s) {
  405.              T defaultValue = default (T);
  406.              return  ConvertTo<T>(s,defaultValue);
  407.          }
  408.          public  static  T ConvertTo<T>(string  s,T defaultValue) {
  409.              if (IsNull(s))
  410.                  return  defaultValue;
  411.              try  {
  412.                  return  (T)Convert .ChangeType(s,typeof (T));
  413.              }
  414.              catch (InvalidCastException ) {
  415.                  return  defaultValue;
  416.              }
  417.          }
  418.          public  static  string  Each(string  s,Func <char ,char > fEach) {
  419.              StringBuilder  sbuilder = new  StringBuilder (s.Length);
  420.              for (int  i = 0;i < s.Length;i++) {
  421.                  char  c = s[i];
  422.                  sbuilder.Append(fEach(c));
  423.              }
  424.              return  sbuilder.ToString();
  425.          }
  426.          public  static  string  Each(string  s,Func <char ,int ,char > fEach) {
  427.              StringBuilder  sbuilder = new  StringBuilder (s.Length);
  428.              for (int  i = 0;i < s.Length;i++) {
  429.                  char  c = s[i];
  430.                  char  r = fEach(c,i);
  431.                  if (r == char .MinValue || r == char .MaxValue)
  432.                      continue ;
  433.                  sbuilder.Append(r.ToString());
  434.              }
  435.              return  sbuilder.ToString();
  436.          }
  437.          public  static  string  RemoveDigits(string  s) {
  438.              return  Each(s,c => {
  439.                  if (char .IsDigit(c))
  440.                      return  char .MinValue;
  441.                  else
  442.                      return  c;
  443.              });
  444.          }
  445.          public  static  string  RemoveNonDigits(string  s) {
  446.              return  Each(s,c => {
  447.                  if (!char .IsDigit(c))
  448.                      return  char .MinValue;
  449.                  else
  450.                      return  c;
  451.              });
  452.          }
  453.          public  static  decimal  ParseOutDigits(string  s) {
  454.              string  digits = string .Empty;
  455.              for (int  i = 0;i < s.Length;i++) {
  456.                  char  c = s[i];
  457.                  if (char .IsDigit(c))
  458.                      digits += c.ToString();
  459.              }
  460.              decimal  results = 0;
  461.              if (decimal .TryParse(digits,out  results))
  462.                  return  results;
  463.              return  0;
  464.          }
  465.          public  static  string  JoinStrings(IEnumerable <string > strings,string  separator) {
  466.              return  string .Join(separator,strings.ToArray());
  467.          }
  468.          public  static  string  JoinStrings(IEnumerable <string > strings,string  separator,int  startIndex,int  count) {
  469.              return  string .Join(separator,strings.ToArray(),startIndex,count);
  470.          }
  471.          public  static  string  Max(string  s,int  maximumLength) {
  472.              return  StringHelper .Truncate(s,maximumLength);
  473.          }
  474.          public  static  string  Max(string  s,int  maximumLength,string  suffix) {
  475.              return  StringHelper .Truncate(s,maximumLength,suffix);
  476.          }
  477.          
  478.          public  static  string  ToSentenceCase(string  s) {
  479.              if (s == null )
  480.                  return  s;
  481.              if (s.Trim().Length == 0)
  482.                  return  s;
  483.  
  484.              var  sb = new  StringBuilder (s.Length);
  485.              var  parts = s.Split(" " .ToCharArray());
  486.  
  487.              for (int  i = 0;i < parts.Length;i++) {
  488.                  char [] word = parts[i].ToCharArray();
  489.                  if (word.Length == 1) {
  490.                      if (char .IsWhiteSpace(word[0])) {
  491.                          sb.Append(word[0]);
  492.                          continue ;
  493.                      }
  494.                  }
  495.                  for (int  j = 0;j < word.Length;j++) {
  496.                      if (j == 0)
  497.                          word[j] = char .ToUpperInvariant(word[j]);
  498.                      else
  499.                          word[j] = char .ToLowerInvariant(word[j]);
  500.                  }
  501.                  sb.Append(new  string (word));
  502.                  sb.Append(" " );
  503.              }
  504.              return  sb.ToString().TrimEnd();
  505.          }
  506.          public  static  string  ToToogleCase(string  s) {
  507.              if (s == null )
  508.                  return  s;
  509.              if (s.Trim().Length == 0)
  510.                  return  s;
  511.  
  512.              var  sb = new  StringBuilder (s.Length);
  513.              var  parts = s.Split(" " .ToCharArray());
  514.              for (int  i = 0;i < parts.Length;i++) {
  515.                  char [] word = parts[i].ToCharArray();
  516.                  if (word.Length == 1) {
  517.                      if (char .IsWhiteSpace(word[0])) {
  518.                          sb.Append(word[0]);
  519.                          continue ;
  520.                      }
  521.                  }
  522.                  for (int  j = 0;j < word.Length;j++) {
  523.                      if (char .IsUpper(word[j]))
  524.                          word[j] = char .ToLowerInvariant(word[j]);
  525.                      else  if (char .IsLower(word[j]))
  526.                          word[j] = char .ToUpperInvariant(word[j]);
  527.                  }
  528.                  sb.Append(new  string (word));
  529.                  sb.Append(" " );
  530.              }
  531.              return  sb.ToString().TrimEnd();
  532.          }
  533.      }
  534.  }
Add Comment
Please, Sign In to add comment