using System; using System.Collections.Generic; using System.Data.Entity.Design.PluralizationServices; using System.Globalization; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; /// /// Contains extension methods. /// public static class StringExtensions { private static Regex titleRegEx; /// /// Initializes the class. /// static StringExtensions() { titleRegEx = new Regex(@" (?<=[A-Z])(?=[A-Z][a-z]) | (?<=[^A-Z])(?=[A-Z]) | (?<=[A-Za-z])(?=[^A-Za-z])", RegexOptions.IgnorePatternWhitespace); } /// /// Converts the object to string. If the object is null, will return null. /// /// The object. /// public static String ToStringSafe(this object obj) { return obj != null ? obj.ToString() : String.Empty; } /// /// Splits the string to lines. /// /// The string. /// public static List ToLines(this String str) { //return str.Split(new[] { '\r', '\n' }).ToList(); if (str == null) return new List(); return str.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None).ToList(); } /// /// Formats the string as title style. /// /// The string. /// public static String ToTitle(this String str) { return titleRegEx.Replace(str, " "); } /// /// Formats the string as title case. /// /// The string. /// public static String ToTitleCase(this String str) { return Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(str.ToLower()); } /// /// Converts the specified database conventional name to the observables conventional name. /// /// DAL name. /// public static String FromDalNameToTitleCase(this String dalName) { return String.Join("", dalName.Split('_').Select(x => ToTitleCase(x))); } /// /// Singularizes the string. /// /// The text. /// public static String SingularizeMVC(this String text) { var serv = PluralizationService.CreateService(new System.Globalization.CultureInfo("en-us")); return serv.Singularize(text); } /// /// Pluralizes the string. /// /// The text. /// public static String PluralizeMVC(this String text) { var serv = PluralizationService.CreateService(new System.Globalization.CultureInfo("en-us")); return serv.Pluralize(text); } /// /// Truncates the specified string to the specified max length and appends ellipsis. /// /// The text. /// Max length /// public static String Ellipsis(this String text, int maxLength) { return text.Length <= maxLength ? text : text.Substring(0, maxLength) + "..."; } /// /// Converts the string to camel case string. /// /// The string. /// public static String ToCamelCase(this String str) { if (String.IsNullOrEmpty(str) || Char.IsLower(str, 0)) return str; return Char.ToLowerInvariant(str[0]) + str.Substring(1); } /// /// Compares the two strings based on letter pair matches /// /// /// /// The percentage match from 0.0 to 1.0 where 1.0 is 100% public static double CompareSimilarity(this string str1, string str2) { List pairs1 = WordLetterPairs(str1.ToUpper()); List pairs2 = WordLetterPairs(str2.ToUpper()); int intersection = 0; int union = pairs1.Count + pairs2.Count; for (int i = 0; i < pairs1.Count; i++) { for (int j = 0; j < pairs2.Count; j++) { if (pairs1[i] == pairs2[j]) { intersection++; pairs2.RemoveAt(j);//Must remove the match to prevent "GGGG" from appearing to match "GG" with 100% success break; } } } return (2.0 * intersection) / union; } /// /// Gets all letter pairs for each /// individual word in the string /// /// /// private static List WordLetterPairs(string str) { List AllPairs = new List(); // Tokenize the string and put the tokens/words into an array string[] Words = Regex.Split(str, @"\s"); // For each word for (int w = 0; w < Words.Length; w++) { if (!string.IsNullOrEmpty(Words[w])) { // Find the pairs of characters String[] PairsInWord = LetterPairs(Words[w]); for (int p = 0; p < PairsInWord.Length; p++) { AllPairs.Add(PairsInWord[p]); } } } return AllPairs; } /// /// Generates an array containing every /// two consecutive letters in the input string /// /// /// private static string[] LetterPairs(string str) { int numPairs = str.Length - 1; string[] pairs = new string[numPairs]; for (int i = 0; i < numPairs; i++) { pairs[i] = str.Substring(i, 2); } return pairs; } /// /// Splits the camel case sentence to words. /// /// The string. /// public static string ToWords(this string str) { return Regex.Replace( Regex.Replace( str, @"(\P{Ll})(\P{Ll}\p{Ll})", "$1 $2" ), @"(\p{Ll})(\P{Ll})", "$1 $2" ); } /// /// Removes any invalid file name characters from the string. /// /// The string. /// public static string ToValidFileName(this string str) { char[] _invalidChars = System.IO.Path.GetInvalidFileNameChars(); String validFileName = str; if (validFileName != null) { foreach (var c in _invalidChars) { validFileName = validFileName.Replace(c.ToString(), ""); } } return validFileName; } public static String ToStringOrEmpty(this String str) { return str != null ? str : String.Empty; } public static String ToNullIfEmpty(this String str) { return String.IsNullOrEmpty(str) ? null : str; } public static bool IsNotNullOrEmpty(this String str) { return !String.IsNullOrWhiteSpace(str); } public static String ToOneLine(this String str) { return str.Replace(Environment.NewLine, " "); } public static List ToEnumValues(this String str, char splitChar) where T : struct { if (!String.IsNullOrWhiteSpace(str)) { return str.Split(splitChar).Select(x => (T)(object)int.Parse(x)).ToList(); } else { return new List(); } } public static IEnumerable AllIndexesOf(this string str, string searchstring) { int minIndex = str.IndexOf(searchstring); while (minIndex != -1) { yield return minIndex; minIndex = str.IndexOf(searchstring, minIndex + searchstring.Length); } } }