Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //-----------------------------------------------------------------------
- // <copyright file="StringExtensions.cs" company="Telerik Academy">
- // All rights reserved © Telerik Academy 2012-2013
- // </copyright>
- //-----------------------------------------------------------------------
- namespace Telerik.ILS.Common
- {
- using System;
- using System.Collections.Generic;
- using System.Globalization;
- using System.Linq;
- using System.Security.Cryptography;
- using System.Text;
- using System.Text.RegularExpressions;
- /// <summary>
- /// Extension methods for the <see cref="System.String"/> class.
- /// </summary>
- public static class StringExtensions
- {
- /// <summary>
- /// Computes the hash of the input string using the MD5 Message-Digest Algorithm. It converts the input string to a byte array and formats it as a hexadecimal string.
- /// </summary>
- /// <param name="input">The input gets the string whose MD5 hash the method computes.</param>
- /// <returns>Hexadecimal string of the computed hash of the input string</returns>
- /// <example>
- /// How to use the <see cref="ToMD5Hash"/> method
- /// <code>
- /// class TestClass
- /// {
- /// static void Main()
- /// {
- /// string value = "test";
- /// Console.WriteLine(value.ToMD5Hash());
- /// }
- /// }
- /// </code>
- /// </example>
- /// <seealso cref="http://en.wikipedia.org/wiki/Md5"/>
- public static string ToMd5Hash(this string input)
- {
- var md5Hash = MD5.Create();
- var hashArray = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
- var hexadecimalStringBuilder = new StringBuilder();
- for (int i = 0; i < hashArray.Length; i++)
- {
- hexadecimalStringBuilder.Append(hashArray[i].ToString("x2"));
- }
- return hexadecimalStringBuilder.ToString();
- }
- /// <summary>
- /// Checks if the input string is among the specified values that qualify as <see cref="System.Boolean"/> 'true'
- /// </summary>
- /// <param name="input"> Gets the string that should be checked</param>
- /// <returns><see cref="System.Boolean"/> true or false depending on the presence of the input string in the array of 'true' values</returns>
- /// <example>
- /// How to use the <see cref="ToBoolean"/> method.
- /// <code>
- /// class TestClass
- /// {
- /// static void Main()
- /// {
- /// string value = "ok";
- /// Console.WriteLine(value.ToBoolean());
- /// }
- /// }
- /// </code>
- /// </example>
- public static bool ToBoolean(this string input)
- {
- var trueValuesArray = new[] { "true", "ok", "yes", "1", "да" };
- bool isTrueInput = trueValuesArray.Contains(input.ToLower());
- return isTrueInput;
- }
- /// <summary>
- /// Converts the input string to <see cref="System.Int16"/>.
- /// </summary>
- /// <param name="input">Gets the string to be converted</param>
- /// <returns>The converted to <see cref="System.Int16"/> string</returns>
- /// <example>
- /// How to use the <see cref="ToShort"/> method.
- /// <code>
- /// class TestClass
- /// {
- /// static void Main()
- /// {
- /// string value = "3435";
- /// Console.WriteLine(value.ToShort());
- /// }
- /// }
- /// </code>
- /// </example>
- public static short ToShort(this string input)
- {
- short shortValue;
- short.TryParse(input, out shortValue);
- return shortValue;
- }
- /// <summary>
- /// Converts the input string to <see cref="System.Int32"/>.
- /// </summary>
- /// <param name="input">Gets the string to be converted</param>
- /// <returns>The converted to <see cref="System.Int32"/> string</returns>
- /// <example>
- /// How to use the <see cref="ToInteger"/> method.
- /// <code>
- /// class TestClass
- /// {
- /// static void Main()
- /// {
- /// string value = "1234";
- /// Console.WriteLine(value.ToInteger());
- /// }
- /// }
- /// </code>
- /// </example>
- public static int ToInteger(this string input)
- {
- int integerValue;
- int.TryParse(input, out integerValue);
- return integerValue;
- }
- /// <summary>
- /// Converts the input string to <see cref="System.Int64"/>.
- /// </summary>
- /// <param name="input">Gets the string to be converted</param>
- /// <returns>The converted to <see cref="System.Int64"/> string</returns>
- /// <example>
- /// How to use the <see cref="ToLong"/> method.
- /// <code>
- /// class TestClass
- /// {
- /// static void Main()
- /// {
- /// string value = "1234567";
- /// Console.WriteLine(value.ToLong());
- /// }
- /// }
- /// </code>
- /// </example>
- public static long ToLong(this string input)
- {
- long longValue;
- long.TryParse(input, out longValue);
- return longValue;
- }
- /// <summary>
- /// Converts the input string to <see cref="System.DateTime"/>.
- /// </summary>
- /// <param name="input">Gets the string to be converted</param>
- /// <returns>The converted to <see cref="System.DateTime"/> date</returns>
- /// <example>
- /// How to use the <see cref="ToDateTime"/> method.
- /// <code>
- /// class TestClass
- /// {
- /// static void Main()
- /// {
- /// string value = "2013/3/31 10:30:00";
- /// Console.WriteLine(value.ToDateTime());
- /// }
- /// }
- /// </code>
- /// </example>
- public static DateTime ToDateTime(this string input)
- {
- DateTime dateTimeValue;
- DateTime.TryParse(input, out dateTimeValue);
- return dateTimeValue;
- }
- /// <summary>
- /// Capitalizes the first letter of non-empty string
- /// </summary>
- /// <param name="input">String whose first letter should be capitalized</param>
- /// <returns>The input string with the first letter in upper case or empty string if the string ahs been empty.</returns>
- /// <example>
- /// How to use the <see cref="CapitalizeFirstLetter"/> method.
- /// <code>
- /// class TestClass
- /// {
- /// static void Main()
- /// {
- /// string value = "something to test with.";
- /// Console.WriteLine(value.CapitalizeFirstLetter()); //Output: Something to test with.
- /// }
- /// }
- /// </code>
- /// </example>
- public static string CapitalizeFirstLetter(this string input)
- {
- if (string.IsNullOrEmpty(input))
- {
- return input;
- }
- else
- {
- var capitalizedInput = input.Substring(0, 1).ToUpper(CultureInfo.CurrentCulture) + input.Substring(1, input.Length - 1);
- return capitalizedInput;
- }
- }
- /// <summary>
- /// Returns a substring between <paramref name="startString"/> and <paramref name="endString"/>.
- /// The search starts from <paramref name="startFrom"/> index.
- /// </summary>
- /// <param name="input">The initial string</param>
- /// <param name="startString">The starting point of the result string.</param>
- /// <param name="endString">The ending point of the result string.</param>
- /// <param name="startFromIndex">The start index of the search.</param>
- /// <returns>A substring of the initial string that is between the <paramref name="startString"/>
- /// and the <paramref name="endString"/> searching from the <paramref name="startFromIndex"/> index or System.String.Empty
- /// if <paramref name="startString"/> or <paramref name="endString"/> are not found in the initial string.</returns>
- /// <example>
- /// How to use the <see cref="GetStringBetween"/> method.
- /// <code>
- /// class TestClass
- /// {
- /// static void Main()
- /// {
- /// string value = "If I want to start here and see all these things until I end here.";
- /// Console.WriteLine(value.GetStringBetween("start here", "end here", 10));
- /// }
- /// }
- /// </code>
- /// </example>
- public static string GetStringBetween(this string input, string startString, string endString, int startFromIndex)
- {
- input = input.Substring(startFromIndex);
- startFromIndex = 0;
- if (!input.Contains(startString) || !input.Contains(endString))
- {
- return string.Empty;
- }
- var startPosition = input.IndexOf(startString, startFromIndex, StringComparison.Ordinal) + startString.Length;
- if (startPosition == -1)
- {
- return string.Empty;
- }
- var endPosition = input.IndexOf(endString, startPosition, StringComparison.Ordinal);
- if (endPosition == -1)
- {
- return string.Empty;
- }
- return input.Substring(startPosition, endPosition - startPosition);
- }
- /// <summary>
- /// Replaces all Cyrillic letters in the input string with their Latin counterparts.
- /// </summary>
- /// <param name="input">The string to be converted.</param>
- /// <returns>A string with latin letters.</returns>
- /// <example>
- /// How to use the <see cref="ConvertCyrillicToLatinLetters"/> method.
- /// <code>
- /// class TestClass
- /// {
- /// static void Main()
- /// {
- /// string value = "Букви за преминаване към латиница";
- /// Console.WriteLine(value.ConvertCyrillicToLatinLetters());
- /// }
- /// }
- /// </code>
- /// </example>
- public static string ConvertCyrillicToLatinLetters(this string input)
- {
- var bulgarianLetters = new[]
- {
- "а", "б", "в", "г", "д", "е", "ж", "з", "и", "й", "к", "л", "м", "н", "о", "п",
- "р", "с", "т", "у", "ф", "х", "ц", "ч", "ш", "щ", "ъ", "ь", "ю", "я"
- };
- var latinRepresentationsOfBulgarianLetters = new[]
- {
- "a", "b", "v", "g", "d", "e", "j", "z", "i", "y", "k",
- "l", "m", "n", "o", "p", "r", "s", "t", "u", "f", "h",
- "c", "ch", "sh", "sht", "u", "i", "yu", "ya"
- };
- for (var i = 0; i < bulgarianLetters.Length; i++)
- {
- input = input.ToLowerInvariant();
- input = input.Replace(bulgarianLetters[i], latinRepresentationsOfBulgarianLetters[i]);
- input = input.Replace(bulgarianLetters[i].ToUpper(), latinRepresentationsOfBulgarianLetters[i].CapitalizeFirstLetter());
- }
- return input;
- }
- /// <summary>
- /// Replaces all Latin letters in the input string with their Cyrillic counterparts.
- /// </summary>
- /// <param name="input">The string to be converted.</param>
- /// <returns>A string with cyrillic letters.</returns>
- /// <example>
- /// How to use the <see cref="ConvertCyrillicToLatinLetters"/> method.
- /// <code>
- /// class TestClass
- /// {
- /// static void Main()
- /// {
- /// string value = "Bukvi za preminavane kym kirilica";
- /// Console.WriteLine(value.ConvertCyrillicToLatinLetters());
- /// }
- /// }
- /// </code>
- /// </example>
- public static string ConvertLatinToCyrillicLetters(this string input)
- {
- var latinLetters = new[]
- {
- "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p",
- "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"
- };
- var bulgarianRepresentationOfLatinLetters = new[]
- {
- "а", "б", "ц", "д", "е", "ф", "г", "х", "и", "й", "к",
- "л", "м", "н", "о", "п", "я", "р", "с", "т", "у", "ж",
- "в", "ь", "ъ", "з"
- };
- for (int i = 0; i < latinLetters.Length; i++)
- {
- input = input.ToLowerInvariant();
- input = input.Replace(latinLetters[i], bulgarianRepresentationOfLatinLetters[i]);
- input = input.Replace(latinLetters[i].ToUpper(), bulgarianRepresentationOfLatinLetters[i].ToUpper());
- }
- return input;
- }
- /// <summary>
- /// Makes a user name valid by replacing all Cyrillic letters with their Latin equivalents and removing all non-alphanumeric characters except for the period (".") in the typed user name.
- /// </summary>
- /// <param name="input">User name</param>
- /// <returns>A valid user name (allowed symbols: latin letters and a period)</returns>
- /// <example>
- /// How to use the <see cref="ToValidUsername"/> method.
- /// <code>
- /// class TestClass
- /// {
- /// static void Main()
- /// {
- /// string value = "#$иван.иванов!@#";
- /// Console.WriteLine(value.ToValidUsername());// Output: иван.иванов
- /// }
- /// }
- /// </code>
- /// </example>
- public static string ToValidUsername(this string input)
- {
- input = input.ConvertCyrillicToLatinLetters();
- return Regex.Replace(input, @"[^a-zA-z0-9_\.]+", string.Empty);
- }
- /// <summary>
- /// Makes a file name valid by replacing all Cyrillic letters with their Latin equivalents, all spaces are with hyphens and by removing all non-alphanumeric characters excluding hyphens and periods.
- /// </summary>
- /// <param name="input">File name.</param>
- /// <returns>Valid file name (allowed symbols: latin letters, hyphens and periods)</returns>
- /// <example>
- /// How to use the <see cref="ToValidLatinFileName"/> method.
- /// <code>
- /// class TestClass
- /// {
- /// static void Main()
- /// {
- /// string value = "Файл 30 раздел едно №$ 9А.docx";
- /// Console.WriteLine(value.ToValidLatinFileName()); // Output: Fail-razdel-edno-a.docx
- /// }
- /// }
- /// </code>
- /// </example>
- public static string ToValidLatinFileName(this string input)
- {
- input = input.Replace(" ", "-").ConvertCyrillicToLatinLetters();
- return Regex.Replace(input, @"[^a-zA-z0-9_\.\-]+", string.Empty);
- }
- /// <summary>
- /// Extracts a substring of the input string from the start to a given number of characters <paramref name="charsCount"/> or the end of the string if the total characters are bigger than the input string length.
- /// </summary>
- /// <param name="input">Input string.</param>
- /// <param name="charsCount">The number of characters in the desired substring.</param>
- /// <returns>A substring containing the characters from the start of the input string to the number of characters specified with the <paramref name="charsCount"/> or to the end of the input string.</returns>
- /// <example>
- /// How to use the <see cref="GetFirstCharacters"/> method.
- /// <code>
- /// class TestClass
- /// {
- /// static void Main()
- /// {
- /// string value = "Playing around with the string values";
- /// Console.WriteLine(value.GetFirstCharacters(14)); // Output: Playing around
- /// }
- /// }
- /// </code>
- /// </example>
- public static string GetFirstCharacters(this string input, int charsCount)
- {
- return input.Substring(0, Math.Min(input.Length, charsCount));
- }
- /// <summary>
- /// Gets the file extension of the inputted as a string file name by splitting the input using the period as a delimiter
- /// </summary>
- /// <param name="fileName">The file name</param>
- /// <returns>Returns the characters after the last found period</returns>
- /// <example>
- /// How to use the <see cref="GetFileExtension"/> method.
- /// <code>
- /// class TestClass
- /// {
- /// static void Main()
- /// {
- /// string value = "Test.cs";
- /// Console.WriteLine(value.GetFileExtension()); //Output: cs
- /// }
- /// }
- /// </code>
- /// </example>
- public static string GetFileExtension(this string fileName)
- {
- if (string.IsNullOrWhiteSpace(fileName))
- {
- return string.Empty;
- }
- string[] fileParts = fileName.Split(new[] { "." }, StringSplitOptions.None);
- if (fileParts.Count() == 1 || string.IsNullOrEmpty(fileParts.Last()))
- {
- return string.Empty;
- }
- return fileParts.Last().Trim().ToLower();
- }
- /// <summary>
- /// Returns the corresponding content type (a.k.a. Internet media type) for the specified file extension.
- /// </summary>
- /// <param name="fileExtension">File extension</param>
- /// <returns>The content type</returns>
- /// <example>
- /// How to use the <see cref="ToContentType"/> method.
- /// <code>
- /// class TestClass
- /// {
- /// static void Main()
- /// {
- /// string value = "png";
- /// Console.WriteLine(value.ToContentType());
- /// }
- /// }
- /// </code>
- /// </example>
- /// <seealso cref="http://en.wikipedia.org/wiki/Content_type"/>
- public static string ToContentType(this string fileExtension)
- {
- var fileExtensionToContentType = new Dictionary<string, string>
- {
- { "jpg", "image/jpeg" },
- { "jpeg", "image/jpeg" },
- { "png", "image/x-png" },
- {
- "docx",
- "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
- },
- { "doc", "application/msword" },
- { "pdf", "application/pdf" },
- { "txt", "text/plain" },
- { "rtf", "application/rtf" }
- };
- if (fileExtensionToContentType.ContainsKey(fileExtension.Trim()))
- {
- return fileExtensionToContentType[fileExtension.Trim()];
- }
- return "application/octet-stream";
- }
- /// <summary>
- /// Converts the input string to a char array and block-copies the specified number of bytes to a byte array without offset.
- /// </summary>
- /// <param name="input">Input string</param>
- /// <returns>A byte array</returns>
- public static byte[] ToByteArray(this string input)
- {
- var bytesArray = new byte[input.Length * sizeof(char)];
- Buffer.BlockCopy(input.ToCharArray(), 0, bytesArray, 0, bytesArray.Length);
- return bytesArray;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement