Skip to content

Instantly share code, notes, and snippets.

@antonio-leonardo
Last active July 18, 2019 19:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save antonio-leonardo/9fb8a577820956ebe6ef02ad9cd96075 to your computer and use it in GitHub Desktop.
Save antonio-leonardo/9fb8a577820956ebe6ef02ad9cd96075 to your computer and use it in GitHub Desktop.
C# Extension class that constains several roles to manipulate strings and chars
//Author: Antonio Leonardo de Abreu Freire, Microsoft Certified ID: 13271836
using System;
using System.Web;
using System.Linq;
using System.Collections.Generic;
namespace ExtensionFunctions
{
/// <summary>
/// Reference option for capturing from the beginning or end of the String through the frame
/// </summary>
public enum ReferencePosition
{
First,
Last
}
/// <summary>
/// Options for validating candidate string under a collection of strings
/// </summary>
public enum TypeOfValidationStringOnStringCollection
{
/// <summary>
/// If the validation of the string will be by the evidence at the beginning of the string
/// </summary>
StarsWith,
/// <summary>
/// If the validation of the string will be by the evidence at the end of the string
/// </summary>
EndsWith,
/// <summary>
/// If the validation of the string will be by the evidence in the contents of the string (regardless of whether it is at the beginning or at the end)
/// </summary>
Contains,
/// <summary>
/// If the validation of the string will be by equal evidence of the string
/// </summary>
Equals
}
/// <summary>
/// Extension Features for Strings manipulation
/// </summary>
public static class StringProcessment
{
/// <summary>
/// Returns the first string of characters in a target string from the first character to the frame character (identified by its number)
/// </summary>
/// <param name="targetString">Candidate string</param>
/// <param name="targetCharNumber">Integer for the frame character in the target string, to count the characters</param>
/// <returns>System.String</returns>
public static string GetFirstQuantityChars(this string targetString, int targetCharNumber)
{
return targetString.Substring(0, Math.Min(targetString.Length, targetCharNumber));
}
/// <summary>
/// Returns the first character string based on a character or string frame
/// </summary>
/// <param name="targetString">Candidate string</param>
/// <param name="startFrom">Caracter or string frame</param>
/// <param name="positionReference">Set 'First' if the capture will be from the first found reference of the String of the parameter 'startFrom' or 'Last' if the capture will be from the last reference of the parameter 'startFrom'</param>
/// <returns>System.String</returns>
public static string GetBeforeString(this string targetString, string startFrom, ReferencePosition positionReference)
{
string returning = null;
switch (positionReference)
{
case ReferencePosition.First:
returning = targetString.Substring(0, targetString.IndexOf(startFrom));
break;
case ReferencePosition.Last:
returning = targetString.Substring(0, targetString.LastIndexOf(startFrom));
break;
}
return returning;
}
/// <summary>
/// Removes a string found in the candidate string
/// </summary>
/// <param name="targetString">Candidate string</param>
/// <param name="searchedString">String to be searched for and removed</param>
/// <returns>System.String</returns>
public static string RemoveInnerString(this string targetString, string searchedString)
{
int position = targetString.IndexOf(searchedString);
if (position >= 0)
{
targetString = targetString.Remove(position, searchedString.Length);
}
return targetString;
}
/// <summary>
/// Returns the string between 2 strings beginning and ending
/// </summary>
/// <param name="targetString">Candiate string</param>
/// <param name="firstString">First String</param>
/// <param name="lastString">Last String</param>
/// <returns>System.String</returns>
public static string GetBetweenStrings(this string targetString, string firstString, string lastString)
{
string finalString = null;
int pos1 = targetString.IndexOf(firstString) + firstString.Length;
int pos2 = targetString.LastIndexOf(lastString);
try
{
finalString = targetString.Substring(pos1, pos2 - pos1);
}
catch
{
finalString = "";
}
return finalString;
}
/// <summary>
/// Get a string after a frame character or string
/// </summary>
/// <param name="targetString">Candidate string</param>
/// <param name="startFrom">String-start strings for capturing strings</param>
/// <param name="positionReference">Set 'First' if the capture will be from the first found reference of the String of the parameter 'startFrom' or 'Last' if the capture will be from the last reference of the parameter 'startFrom'</param>
/// <returns>System.String</returns>
public static string GetAfterStrings(this string targetString, string startFrom, ReferencePosition positionReference)
{
string returning = null;
switch (positionReference)
{
case ReferencePosition.First:
returning = targetString.Substring(targetString.IndexOf(startFrom) + 1);
break;
case ReferencePosition.Last:
returning = targetString.Substring(targetString.LastIndexOf(startFrom) + 1);
break;
}
return returning;
}
/// <summary>
/// Remove the character or characters defined in parameter
/// </summary>
/// <param name="targetString">Candidate string</param>
/// <param name="chars">Character or characters to be removed</param>
/// <returns>System.String</returns>
public static string RemoveCharsOfString(this string targetString, string chars)
{
while (targetString.Contains(chars))
{
targetString = targetString.Replace(chars, "");
}
return targetString;
}
/// <summary>
/// Replace all special characters by character set in parameter
/// </summary>
/// <param name="targetString">Candidate string, with special char on body</param>
/// <param name="charToReplace">Replacement character or characters</param>
/// <returns>System.String</returns>
public static string ReplaceSpecialCharsOfString(this string targetString, string charToReplace)
{
return System.Text.RegularExpressions.Regex
.Replace(targetString, @"[^0-9a-zA-Z]+", charToReplace)
.Replace(" ", charToReplace);
}
/// <summary>
/// Decode character-HTML entities from a URL
/// </summary>
/// <param name="targetString">Candidate string</param>
/// <returns>System.String</returns>
public static string UrlDecode(this string targetString)
{
return Uri.UnescapeDataString(targetString);
}
/// <summary>
/// Decode the candidate string from ASCII to UTF8
/// </summary>
/// <param name="stringEntrada">Candidate string</param>
/// <returns>System.String</returns>
public static string HTMLDecode(this string stringEntrada)
{
return HttpUtility.HtmlDecode(stringEntrada);
}
/// <summary>
/// Get the original URL for consumption of documents and information
/// </summary>
/// <param name="codedUrl">Coded URL</param>
/// <returns>System.String</returns>
public static string OriginalURL(this string codedUrl)
{
return codedUrl.Replace(" ", "%20");
}
/// <summary>
/// Randomizes a sequence of numbers to a string
/// </summary>
/// <param name="value">The string which will be filled with the random number</param>
/// <param name="length">The number of characters will be filled</param>
/// <returns>System.String</returns>
public static string RandomNumbers(this string value, int length)
{
Random rnd = new Random();
for (int i = 0; i <= length; i++)
{
value += rnd.Next(0, 9);
}
return value;
}
/// <summary>
/// Removes special characters from a String
/// </summary>
/// <param name="value">Candidate string</param>
/// <returns>System.String</returns>
public static string RemoveSpecialChars(this string value)
{
if (string.IsNullOrWhiteSpace(value))
return string.Empty;
return new System.Text.RegularExpressions.Regex("[;\\\\/:*?\"<>|=&--'.¨$#%-+,!@()_]").Replace(value, "").Replace(" ", "");
}
/// <summary>
/// Checks if all characters are the same
/// </summary>
/// <param name="value">Candidate string</param>
/// <returns>System.Boolean</returns>
public static bool AllCharsAreEqual(this string value)
{
return value.Distinct().Count() == 1;
}
/// <summary>
/// Remove items from a collection of strings
/// </summary>
/// <param name="collection">Strings Collection</param>
/// <param name="typeOfValidation">Type of validation to be contemplated</param>
/// <param name="collectionToBeRemoved">Collection to have items to remove</param>
/// <returns>System.Collections.Generic.IEnumerable with System.String</returns>
public static IEnumerable<string> RemoveItemsFromStringCollection(
this IEnumerable<string> collection, TypeOfValidationStringOnStringCollection typeOfValidation, params string[] collectionToBeRemoved)
{
foreach (string item in collection)
{
if (!(item.ValidateOneStringOnStringCollection(typeOfValidation, collectionToBeRemoved)))
{
yield return item;
}
}
}
/// <summary>
/// It is in charge of adding pre or post fixed in each item of the collection of strings
/// </summary>
/// <param name="collection">Strings collection</param>
/// <param name="fix">Prefix or Suffix</param>
/// <param name="preOrPosFix">Boolean that define whether it will be pre or post fixed (true = prefix, false = sufixe)</param>
/// <param name="typeOfValidation">Type of validation you should do</param>
/// <param name="itemsCondition">Collection to base the addition validation of pre or post fixed</param>
/// <returns>System.Collections.Generic.IEnumerable with System.String</returns>
public static IEnumerable<string> AddFixInEachItemCollectionBasedInCondition(
this IEnumerable<string> collection, string fix, bool preOrPosFix,
TypeOfValidationStringOnStringCollection typeOfValidation, params string[] itemsCondition)
{
if (preOrPosFix)
{
foreach (string item in collection)
{
if (item.ValidateOneStringOnStringCollection(typeOfValidation, itemsCondition))
{
yield return fix + item;
}
else
{
yield return item;
}
}
}
else
{
foreach (string item in collection)
{
if (item.ValidateOneStringOnStringCollection(typeOfValidation, itemsCondition))
{
yield return item + fix;
}
else
{
yield return item;
}
}
}
}
/// <summary>
/// Find common strings on Array of string
/// </summary>
/// <param name="strings">Collection of string</param>
/// <returns>String collection</returns>
public static IEnumerable<string> FindCommonStringsOnArrayOfString(List<string> strings)
{
Tuple<string, string>[] combinations = new Tuple<string, string>[] { };
combinations = CombineArrayOfStringTwoByTwo(false, strings).ToArray();
for (int x = 0; x < combinations.Length; x++)
{
string result = FindCommonStringOnTwoStrings(combinations[x].Item1, combinations[x].Item2);
if (!string.IsNullOrWhiteSpace(result))
{
yield return result;
}
}
}
/// <summary>
/// Find common strings on Array of string
/// </summary>
/// <param name="strings">Collection of string</param>
/// <returns>String collection</returns>
public static IEnumerable<string> FindCommonStringsOnArrayOfString(params string[] strings)
{
Tuple<string, string>[] combinations = new Tuple<string, string>[] { };
combinations = CombineArrayOfStringTwoByTwo(false, strings).ToArray();
for (int x = 0; x < combinations.Length; x++)
{
string result = FindCommonStringOnTwoStrings(combinations[x].Item1, combinations[x].Item2);
if (!string.IsNullOrWhiteSpace(result))
{
yield return result;
}
}
}
/// <summary>
/// Get the common string by two string
/// </summary>
/// <param name="word1">First string</param>
/// <param name="word2">Other String</param>
/// <returns>System.String</returns>
public static string FindCommonStringOnTwoStrings(string word1, string word2)
{
string common = null;
if (!string.IsNullOrWhiteSpace(word1) && !string.IsNullOrWhiteSpace(word2))
{
int index = 0;
bool same = true;
do
{
if (word1[index] == word2[index])
{
common += word1[index];
++index;
}
else
{
same = false;
}
} while (same && index < word1.Length && index < word2.Length);
}
return common;
}
/// <summary>
/// Combine Array of String Two by Two, with a possibilite to repeat or not repeat the result
/// </summary>
/// <param name="repeat">Choose if will repeat the result or not</param>
/// <param name="strings">Array of strings that will combine</param>
/// <returns>Tuple collections of string pair</returns>
public static IEnumerable<Tuple<string, string>> CombineArrayOfStringTwoByTwo(bool repeat, params string[] strings)
{
Dictionary<string, List<string>> iDic = new Dictionary<string, List<string>>();
for (int i = 0; i < strings.Length; i++)
{
iDic.Add(strings[i], new List<string>());
for (int j = 0; j < strings.Length; j++)
{
bool innerRepeat = (!repeat) ? ((strings[j] != strings[i]) && (iDic.ContainsKey(strings[j]) && !iDic[strings[j]].Contains(strings[i]))) : true;
if (innerRepeat)
{
iDic[strings[i]].Add(strings[j]);
}
}
}
foreach (KeyValuePair<string, List<string>> item in iDic)
{
for (int n = 0; n < iDic[item.Key].Count; n++)
{
yield return new Tuple<string, string>(item.Key, iDic[item.Key][n]);
}
}
}
/// <summary>
/// Combine Array of String Two by Two, with a possibilite to repeat or not repeat the result
/// </summary>
/// <param name="repeat">Choose if will repeat the result or not</param>
/// <param name="strings">Array of strings that will combine</param>
/// <returns>Tuple collections of string pair</returns>
public static IEnumerable<Tuple<string, string>> CombineArrayOfStringTwoByTwo(bool repeat, List<string> strings)
{
Dictionary<string, List<string>> iDic = new Dictionary<string, List<string>>();
for (int i = 0; i < strings.Count; i++)
{
iDic.Add(strings[i], new List<string>());
for (int j = 0; j < strings.Count; j++)
{
bool innerRepeat = (!repeat) ? ((strings[j] != strings[i]) && (iDic.ContainsKey(strings[j]) && !iDic[strings[j]].Contains(strings[i]))) : true;
if (innerRepeat)
{
iDic[strings[i]].Add(strings[j]);
}
}
}
foreach (KeyValuePair<string, List<string>> item in iDic)
{
for (int n = 0; n < iDic[item.Key].Count; n++)
{
yield return new Tuple<string, string>(item.Key, iDic[item.Key][n]);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment