Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Text.RegularExpressions;
- using System.Web;
- namespace BA.Core {
- using System.Linq;
- public static class StringHelper {
- /// <summary>
- /// "4000"
- /// </summary>
- public const int MAX_NVARCHAR_LENGTH = 4000;
- public static string HtmlDecode(string s) {
- return HttpUtility .HtmlDecode(s);
- }
- public static string HtmlEncode(string s) {
- return HttpUtility .HtmlEncode(s);
- }
- public static string UrlDecode(string s) {
- return HttpUtility .UrlDecode(s);
- }
- public static string UrlEncode(string s) {
- return HttpUtility .UrlEncode(s);
- }
- public static string [] SplitNewLines(string s) {
- return s.Split(Environment .NewLine.ToCharArray(),StringSplitOptions .RemoveEmptyEntries);
- }
- public static string [] SplitRemoveEmptyEntries(string s,string separator) {
- if (separator.IsNullOrEmptyTrim())
- return new string [] { };
- return s.Split(separator.ToCharArray(),StringSplitOptions .RemoveEmptyEntries);
- }
- public static string ToBase64String(string s) {
- if (s == null )
- return null ;
- if (s.IsNullOrEmptyTrim() == true )
- return s;
- return Convert .ToBase64String(ASCIIEncoding .Unicode.GetBytes(s));
- }
- public static string FromBase64String(string s) {
- if (s == null )
- return null ;
- if (s.IsNullOrEmptyTrim())
- return s;
- return ASCIIEncoding .Unicode.GetString(Convert .FromBase64String(s));
- }
- public static bool IsNull(string s) {
- return IsNullOrEmptyTrim(s);
- }
- public static bool IsNullOrEmptyTrim(string s) {
- if (s == null )
- return true ;
- if (string .IsNullOrEmpty(s))
- return true ;
- if (s.Equals(Environment .NewLine))
- return false ;
- if (string .IsNullOrEmpty(s.Trim()))
- return true ;
- return false ;
- }
- public static bool IsNullOrEmptyTrim(string s,params char [] trimChars) {
- if (s == null )
- return true ;
- if (string .IsNullOrEmpty(s))
- return true ;
- if (string .IsNullOrEmpty(s.Trim(trimChars)))
- return true ;
- return false ;
- }
- public static string ParseTitleString(string s) {
- if (s == null )
- return null ;
- string result = "" ;
- for (int i = 0;i < s.Length;i++) {
- char c = s[i];
- if (char .IsUpper(c)) {
- if (i != 0) {
- int h = i - 1;
- if (h > -1) {
- char p = s[h];
- if (char .IsUpper(p)) {
- result += c.ToString();
- continue ;
- }
- }
- result += " " ;
- }
- }
- result += c.ToString();
- }
- return result;
- }
- public static string ParseSentenceString(string s) {
- if (s == null )
- return null ;
- string result = "" ;
- bool passfirst = false ;
- for (int i = 0;i < s.Length;i++) {
- char c = s[i];
- if (!char .IsUpper(c)) {
- result += c.ToString();
- continue ;
- }
- if (!passfirst) {
- result += " " ;
- result += c.ToString();
- passfirst = true ;
- }
- else {
- int h = i - 1;
- int j = i + 1;
- bool nextUpper = false ;
- bool previousUpper = false ;
- if (h > -1) {
- char p = s[h];
- if (char .IsUpper(p)) {
- nextUpper = true ;
- }
- }
- if (j < s.Length) {
- char n = s[j];
- if (char .IsUpper(n)) {
- previousUpper = true ;
- }
- }
- if (nextUpper || previousUpper) {
- if (previousUpper) {
- if (!nextUpper)
- result += " " ;
- result += c.ToString();
- }
- else {
- if (nextUpper && previousUpper)
- result += " " + c.ToString();
- else if (nextUpper && !previousUpper)
- result += c.ToString();
- else if (!nextUpper && previousUpper)
- result += c.ToString();
- }
- }
- else
- result += c.ToString().ToLowerInvariant();
- }
- }
- return result;
- }
- public static string Left(string s,int length) {
- if (length < 1)
- return s;
- if (s.Length < length)
- return s;
- return s.Substring(0,length);
- }
- public static string LeftDbMax(string s) {
- int length = MAX_NVARCHAR_LENGTH;
- if (length < 1)
- return s;
- if (s.Length < length)
- return s;
- return s.Substring(0,length);
- }
- public static string RemoveSpaces(string s) {
- if (s == null )
- return null ;
- string result = string .Empty;
- for (int i = 0;i < s.Length;i++) {
- char c = s[i];
- if (char .IsWhiteSpace(c))
- continue ;
- result += c.ToString();
- }
- return result;
- }
- public static string ReplaceNonAlphaNumeric(string s) {
- string build = null ;
- foreach (char c in s.ToCharArray()) {
- if (IsAlphaNumeric(c.ToString()))
- build += c.ToString();
- }
- return build;
- }
- public static bool IsNumeric(string s) {
- if (IsNull(s))
- return false ;
- decimal r = 0;
- if (decimal .TryParse(s,out r))
- return true ;
- return false ;
- }
- // function To test for only Alpha Chars.
- public static bool IsAlpha(string strToCheck) {
- Regex objAlphaPattern = new Regex ("[^a-zA-Z]" );
- return !objAlphaPattern.IsMatch(strToCheck.Replace(" " ,"" ));
- }
- // function to Check for AlphaNumeric.
- public static bool IsAlphaNumeric(string strToCheck) {
- Regex objAlphaNumericPattern = new Regex ("[^a-zA-Z0-9]" );
- return !objAlphaNumericPattern.IsMatch(strToCheck.Replace(" " ,"" ));
- }
- public static string Replace(string s,Dictionary <string ,string > values) {
- StringBuilder builder = new StringBuilder (s);
- foreach (string key in values.Keys) {
- builder.Replace(key,values[key]);
- }
- return builder.ToString();
- }
- public static string Truncate(string s,int maximumLength) {
- return Truncate(s,maximumLength,"..." );
- }
- public static string Truncate(string s,int maximumLength,string suffix) {
- if (suffix == null )
- throw new ArgumentNullException ("suffix" );
- if (maximumLength <= 0)
- throw new ArgumentException ("Maximum length must be greater than zero." ,"maximumLength" );
- int subStringLength = maximumLength - suffix.Length;
- if (subStringLength <= 0)
- throw new ArgumentException ("Length of suffix string is greater or equal to maximumLength" );
- if (s != null && s.Length > maximumLength) {
- string truncatedString = s.Substring(0,subStringLength);
- // incase the last character is a space
- truncatedString = truncatedString.Trim();
- truncatedString += suffix;
- return truncatedString;
- }
- else {
- return s;
- }
- }
- public static T ToEnum<T>(string s) where T:IComparable ,IFormattable {
- T defaultValue = default (T);
- return ToEnum<T>(s,defaultValue);
- }
- public static T ToEnum<T>(string s,T defaultValue) where T:IComparable ,IFormattable {
- T convertedValue = defaultValue;
- if (!string .IsNullOrEmpty(s)) {
- try {
- convertedValue = (T)Enum .Parse(typeof (T),s.Trim(),true );
- }
- catch (ArgumentException ) {
- return defaultValue;
- }
- }
- return convertedValue;
- }
- public static string GetPluralName(string name) {
- int index = name.IndexOf("Of" ,StringComparison .Ordinal);
- if ((((index > 3) && (index < (name.Length - 4))) && (char .IsLower(name,index - 1) && (name[index - 1] != 's' ))) && char .IsUpper(name,index + 2)) {
- return (name.Substring(0,index) + "s" + name.Substring(index));
- }
- string str = "" ;
- string str2 = name.ToLowerInvariant();
- if (str2.EndsWith("created" ,StringComparison .Ordinal) || name.EndsWith("updated" ,StringComparison .Ordinal)) {
- if (name.Length < 10) {
- return name;
- }
- string str3 = str2.Substring(name.Length - 9,2);
- string str4 = str2.Substring(name.Length - 10,3);
- switch (str3) {
- case "co" :
- case "re" :
- case "un" :
- return name;
- }
- switch (str4) {
- case "mis" :
- case "pro" :
- return name;
- }
- str = name.Substring(name.Length - 7);
- name = name.Substring(0,name.Length - 7);
- }
- str2 = name.ToLowerInvariant();
- if ((((!str2.EndsWith("information" ) && !str2.EndsWith("complete" )) && (!str2.EndsWith("_info" ) && !str2.EndsWith("_data" ))) && (!name.EndsWith("Info" ) && !name.EndsWith("Data" ))) && !name.EndsWith("Staff" )) {
- if (((str2.EndsWith("x" ) || str2.EndsWith("ch" )) || str2.EndsWith("ss" )) || str2.EndsWith("status" )) {
- name = name + "es" ;
- }
- else if (!((!str2.EndsWith("y" ) || (str2.Length <= 1)) || IsVowel(str2[str2.Length - 2]))) {
- name = name.Substring(0,name.Length - 1) + "ies" ;
- }
- else if (!str2.EndsWith("s" )) {
- name = name + "s" ;
- }
- }
- string result = (name + str);
- if (result.EqualsIgnoreCase(name)) {
- if (result.EndsWith("s" ))
- result += "es" ;
- else
- result += "s" ;
- }
- return result;
- }
- public static bool IsVowel(char c) {
- return "aeiuo" .Contains<char >(char .ToLowerInvariant(c));
- }
- public static string Repeat(string s,int num) {
- return Repeat(s,num,string .Empty);
- }
- public static string Repeat(string s,int num,string delimeter) {
- if (IsNull(s))
- return s;
- StringBuilder sb = new StringBuilder ();
- for (int i = 0;i < num;i++) {
- sb.Append(s);
- if (delimeter != null )
- sb.Append(delimeter);
- }
- return sb.ToString();
- }
- public static string Repeat(string s,int num,Func <string ,string > actions) {
- if (actions == null )
- return s;
- StringBuilder sbuilder = new StringBuilder ();
- for (int i = 0;i < num;i++) {
- sbuilder.Append(actions(s));
- }
- return sbuilder.ToString();
- }
- public static string Repeat(string s,int num,Func <string ,int ,string > actions) {
- if (actions == null )
- return s;
- StringBuilder sbuilder = new StringBuilder ();
- for (int i = 0;i < num;i++) {
- sbuilder.Append(actions(s,i));
- }
- return sbuilder.ToString();
- }
- public static string TrimStart(string s,string value) {
- if (IsNull(s))
- return s;
- EnsureNotNull(ref value);
- if (s.Length < value.Length)
- return s;
- return s.Substring(0,value.Length);
- }
- public static string TrimEnd(string s,string value) {
- if (IsNull(s))
- return s;
- EnsureNotNull(ref value);
- if (s.Length < value.Length)
- return s;
- return s.Substring(s.Length - value.Length,value.Length);
- }
- public static string Append(string s,string value) {
- return s + EnsureNotNull(value);
- }
- public static string Prepend(string s,string value) {
- return EnsureNotNull(value) + s;
- }
- public static string EnsureNotNull(ref string s) {
- return EnsureNotNull(s);
- }
- public static string EnsureNotNull(string s) {
- if (s == null )
- return string .Empty;
- else
- return s;
- }
- public static string Wrap(string s,string value) {
- EnsureNotNull(ref s);
- EnsureNotNull(ref value);
- return value + s + value;
- }
- public static string WrapInQuotes(string s) {
- return Wrap(s,"'" );
- }
- public static int ToInt32(string s) {
- return ConvertTo<int >(s);
- }
- public static int ToInt32(string s,int defaultValue) {
- return ConvertTo<int >(s,defaultValue);
- }
- public static decimal ToDecimal(string s) {
- return ConvertTo<decimal >(s);
- }
- public static decimal ToDecimal(string s,decimal defaultValue) {
- return ConvertTo<decimal >(s,defaultValue);
- }
- public static float ToFloat(string s) {
- return ConvertTo<float >(s);
- }
- public static float ToFloat(string s,float defaultValue) {
- return ConvertTo<float >(s,defaultValue);
- }
- public static bool ToBool(string s) {
- return ConvertTo<bool >(s);
- }
- public static bool ToBool(string s,bool defaultValue) {
- return ConvertTo<bool >(s,defaultValue);
- }
- public static DateTime ? ToDateTime(string s) {
- return ConvertTo<DateTime ?>(s);
- }
- public static DateTime ? ToDateTime(string s,DateTime defaultValue) {
- return ConvertTo<DateTime ?>(s,defaultValue);
- }
- public static T ConvertTo<T>(string s) {
- T defaultValue = default (T);
- return ConvertTo<T>(s,defaultValue);
- }
- public static T ConvertTo<T>(string s,T defaultValue) {
- if (IsNull(s))
- return defaultValue;
- try {
- return (T)Convert .ChangeType(s,typeof (T));
- }
- catch (InvalidCastException ) {
- return defaultValue;
- }
- }
- public static string Each(string s,Func <char ,char > fEach) {
- StringBuilder sbuilder = new StringBuilder (s.Length);
- for (int i = 0;i < s.Length;i++) {
- char c = s[i];
- sbuilder.Append(fEach(c));
- }
- return sbuilder.ToString();
- }
- public static string Each(string s,Func <char ,int ,char > fEach) {
- StringBuilder sbuilder = new StringBuilder (s.Length);
- for (int i = 0;i < s.Length;i++) {
- char c = s[i];
- char r = fEach(c,i);
- if (r == char .MinValue || r == char .MaxValue)
- continue ;
- sbuilder.Append(r.ToString());
- }
- return sbuilder.ToString();
- }
- public static string RemoveDigits(string s) {
- return Each(s,c => {
- if (char .IsDigit(c))
- return char .MinValue;
- else
- return c;
- });
- }
- public static string RemoveNonDigits(string s) {
- return Each(s,c => {
- if (!char .IsDigit(c))
- return char .MinValue;
- else
- return c;
- });
- }
- public static decimal ParseOutDigits(string s) {
- string digits = string .Empty;
- for (int i = 0;i < s.Length;i++) {
- char c = s[i];
- if (char .IsDigit(c))
- digits += c.ToString();
- }
- decimal results = 0;
- if (decimal .TryParse(digits,out results))
- return results;
- return 0;
- }
- public static string JoinStrings(IEnumerable <string > strings,string separator) {
- return string .Join(separator,strings.ToArray());
- }
- public static string JoinStrings(IEnumerable <string > strings,string separator,int startIndex,int count) {
- return string .Join(separator,strings.ToArray(),startIndex,count);
- }
- public static string Max(string s,int maximumLength) {
- return StringHelper .Truncate(s,maximumLength);
- }
- public static string Max(string s,int maximumLength,string suffix) {
- return StringHelper .Truncate(s,maximumLength,suffix);
- }
- public static string ToSentenceCase(string s) {
- if (s == null )
- return s;
- if (s.Trim().Length == 0)
- return s;
- var sb = new StringBuilder (s.Length);
- var parts = s.Split(" " .ToCharArray());
- for (int i = 0;i < parts.Length;i++) {
- char [] word = parts[i].ToCharArray();
- if (word.Length == 1) {
- if (char .IsWhiteSpace(word[0])) {
- sb.Append(word[0]);
- continue ;
- }
- }
- for (int j = 0;j < word.Length;j++) {
- if (j == 0)
- word[j] = char .ToUpperInvariant(word[j]);
- else
- word[j] = char .ToLowerInvariant(word[j]);
- }
- sb.Append(new string (word));
- sb.Append(" " );
- }
- return sb.ToString().TrimEnd();
- }
- public static string ToToogleCase(string s) {
- if (s == null )
- return s;
- if (s.Trim().Length == 0)
- return s;
- var sb = new StringBuilder (s.Length);
- var parts = s.Split(" " .ToCharArray());
- for (int i = 0;i < parts.Length;i++) {
- char [] word = parts[i].ToCharArray();
- if (word.Length == 1) {
- if (char .IsWhiteSpace(word[0])) {
- sb.Append(word[0]);
- continue ;
- }
- }
- for (int j = 0;j < word.Length;j++) {
- if (char .IsUpper(word[j]))
- word[j] = char .ToLowerInvariant(word[j]);
- else if (char .IsLower(word[j]))
- word[j] = char .ToUpperInvariant(word[j]);
- }
- sb.Append(new string (word));
- sb.Append(" " );
- }
- return sb.ToString().TrimEnd();
- }
- }
- }
Add Comment
Please, Sign In to add comment