| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532 |
- using System;
- using System.Globalization;
- using System.Security.Cryptography;
- using System.Text;
- using System.Text.RegularExpressions;
- using Abp.Collections.Extensions;
- namespace Abp.Extensions
- {
- /// <summary>
- /// Extension methods for String class.
- /// </summary>
- public static class StringExtensions
- {
- /// <summary>
- /// Adds a char to end of given string if it does not ends with the char.
- /// </summary>
- public static string EnsureEndsWith(this string str, char c)
- {
- return EnsureEndsWith(str, c, StringComparison.Ordinal);
- }
- /// <summary>
- /// Adds a char to end of given string if it does not ends with the char.
- /// </summary>
- public static string EnsureEndsWith(this string str, char c, StringComparison comparisonType)
- {
- if (str == null)
- {
- throw new ArgumentNullException(nameof(str));
- }
- if (str.EndsWith(c.ToString(), comparisonType))
- {
- return str;
- }
- return str + c;
- }
- /// <summary>
- /// Adds a char to end of given string if it does not ends with the char.
- /// </summary>
- public static string EnsureEndsWith(this string str, char c, bool ignoreCase, CultureInfo culture)
- {
- if (str == null)
- {
- throw new ArgumentNullException(nameof(str));
- }
- if (str.EndsWith(c.ToString(culture), ignoreCase, culture))
- {
- return str;
- }
- return str + c;
- }
- /// <summary>
- /// Adds a char to beginning of given string if it does not starts with the char.
- /// </summary>
- public static string EnsureStartsWith(this string str, char c)
- {
- return EnsureStartsWith(str, c, StringComparison.Ordinal);
- }
- /// <summary>
- /// Adds a char to beginning of given string if it does not starts with the char.
- /// </summary>
- public static string EnsureStartsWith(this string str, char c, StringComparison comparisonType)
- {
- if (str == null)
- {
- throw new ArgumentNullException(nameof(str));
- }
- if (str.StartsWith(c.ToString(), comparisonType))
- {
- return str;
- }
- return c + str;
- }
- /// <summary>
- /// Adds a char to beginning of given string if it does not starts with the char.
- /// </summary>
- public static string EnsureStartsWith(this string str, char c, bool ignoreCase, CultureInfo culture)
- {
- if (str == null)
- {
- throw new ArgumentNullException("str");
- }
- if (str.StartsWith(c.ToString(culture), ignoreCase, culture))
- {
- return str;
- }
- return c + str;
- }
- /// <summary>
- /// Indicates whether this string is null or an System.String.Empty string.
- /// </summary>
- public static bool IsNullOrEmpty(this string str)
- {
- return string.IsNullOrEmpty(str);
- }
- /// <summary>
- /// indicates whether this string is null, empty, or consists only of white-space characters.
- /// </summary>
- public static bool IsNullOrWhiteSpace(this string str)
- {
- return string.IsNullOrWhiteSpace(str);
- }
- /// <summary>
- /// Gets a substring of a string from beginning of the string.
- /// </summary>
- /// <exception cref="ArgumentNullException">Thrown if <paramref name="str"/> is null</exception>
- /// <exception cref="ArgumentException">Thrown if <paramref name="len"/> is bigger that string's length</exception>
- public static string Left(this string str, int len)
- {
- if (str == null)
- {
- throw new ArgumentNullException("str");
- }
- if (str.Length < len)
- {
- throw new ArgumentException("len argument can not be bigger than given string's length!");
- }
- return str.Substring(0, len);
- }
- /// <summary>
- /// Converts line endings in the string to <see cref="Environment.NewLine"/>.
- /// </summary>
- public static string NormalizeLineEndings(this string str)
- {
- return str.Replace("\r\n", "\n").Replace("\r", "\n").Replace("\n", Environment.NewLine);
- }
- /// <summary>
- /// Gets index of nth occurence of a char in a string.
- /// </summary>
- /// <param name="str">source string to be searched</param>
- /// <param name="c">Char to search in <see cref="str"/></param>
- /// <param name="n">Count of the occurence</param>
- public static int NthIndexOf(this string str, char c, int n)
- {
- if (str == null)
- {
- throw new ArgumentNullException(nameof(str));
- }
- var count = 0;
- for (var i = 0; i < str.Length; i++)
- {
- if (str[i] != c)
- {
- continue;
- }
- if ((++count) == n)
- {
- return i;
- }
- }
- return -1;
- }
- /// <summary>
- /// Removes first occurrence of the given postfixes from end of the given string.
- /// Ordering is important. If one of the postFixes is matched, others will not be tested.
- /// </summary>
- /// <param name="str">The string.</param>
- /// <param name="postFixes">one or more postfix.</param>
- /// <returns>Modified string or the same string if it has not any of given postfixes</returns>
- public static string RemovePostFix(this string str, params string[] postFixes)
- {
- if (str == null)
- {
- return null;
- }
- if (str == string.Empty)
- {
- return string.Empty;
- }
- if (postFixes.IsNullOrEmpty())
- {
- return str;
- }
- foreach (var postFix in postFixes)
- {
- if (str.EndsWith(postFix))
- {
- return str.Left(str.Length - postFix.Length);
- }
- }
- return str;
- }
- /// <summary>
- /// Removes first occurrence of the given prefixes from beginning of the given string.
- /// Ordering is important. If one of the preFixes is matched, others will not be tested.
- /// </summary>
- /// <param name="str">The string.</param>
- /// <param name="preFixes">one or more prefix.</param>
- /// <returns>Modified string or the same string if it has not any of given prefixes</returns>
- public static string RemovePreFix(this string str, params string[] preFixes)
- {
- if (str == null)
- {
- return null;
- }
- if (str == string.Empty)
- {
- return string.Empty;
- }
- if (preFixes.IsNullOrEmpty())
- {
- return str;
- }
- foreach (var preFix in preFixes)
- {
- if (str.StartsWith(preFix))
- {
- return str.Right(str.Length - preFix.Length);
- }
- }
- return str;
- }
- /// <summary>
- /// Gets a substring of a string from end of the string.
- /// </summary>
- /// <exception cref="ArgumentNullException">Thrown if <paramref name="str"/> is null</exception>
- /// <exception cref="ArgumentException">Thrown if <paramref name="len"/> is bigger that string's length</exception>
- public static string Right(this string str, int len)
- {
- if (str == null)
- {
- throw new ArgumentNullException("str");
- }
- if (str.Length < len)
- {
- throw new ArgumentException("len argument can not be bigger than given string's length!");
- }
- return str.Substring(str.Length - len, len);
- }
- /// <summary>
- /// Uses string.Split method to split given string by given separator.
- /// </summary>
- public static string[] Split(this string str, string separator)
- {
- return str.Split(new[] { separator }, StringSplitOptions.None);
- }
- /// <summary>
- /// Uses string.Split method to split given string by given separator.
- /// </summary>
- public static string[] Split(this string str, string separator, StringSplitOptions options)
- {
- return str.Split(new[] { separator }, options);
- }
- /// <summary>
- /// Uses string.Split method to split given string by <see cref="Environment.NewLine"/>.
- /// </summary>
- public static string[] SplitToLines(this string str)
- {
- return str.Split(Environment.NewLine);
- }
- /// <summary>
- /// Uses string.Split method to split given string by <see cref="Environment.NewLine"/>.
- /// </summary>
- public static string[] SplitToLines(this string str, StringSplitOptions options)
- {
- return str.Split(Environment.NewLine, options);
- }
- /// <summary>
- /// Converts PascalCase string to camelCase string.
- /// </summary>
- /// <param name="str">String to convert</param>
- /// <param name="invariantCulture">Invariant culture</param>
- /// <returns>camelCase of the string</returns>
- public static string ToCamelCase(this string str, bool invariantCulture = true)
- {
- if (string.IsNullOrWhiteSpace(str))
- {
- return str;
- }
- if (str.Length == 1)
- {
- return invariantCulture ? str.ToLowerInvariant() : str.ToLower();
- }
- return (invariantCulture ? char.ToLowerInvariant(str[0]) : char.ToLower(str[0])) + str.Substring(1);
- }
- /// <summary>
- /// Converts PascalCase string to camelCase string in specified culture.
- /// </summary>
- /// <param name="str">String to convert</param>
- /// <param name="culture">An object that supplies culture-specific casing rules</param>
- /// <returns>camelCase of the string</returns>
- public static string ToCamelCase(this string str, CultureInfo culture)
- {
- if (string.IsNullOrWhiteSpace(str))
- {
- return str;
- }
- if (str.Length == 1)
- {
- return str.ToLower(culture);
- }
- return char.ToLower(str[0], culture) + str.Substring(1);
- }
- /// <summary>
- /// Converts given PascalCase/camelCase string to sentence (by splitting words by space).
- /// Example: "ThisIsSampleSentence" is converted to "This is a sample sentence".
- /// </summary>
- /// <param name="str">String to convert.</param>
- /// <param name="invariantCulture">Invariant culture</param>
- public static string ToSentenceCase(this string str, bool invariantCulture = false)
- {
- if (string.IsNullOrWhiteSpace(str))
- {
- return str;
- }
- return Regex.Replace(
- str,
- "[a-z][A-Z]",
- m => m.Value[0] + " " + (invariantCulture ? char.ToLowerInvariant(m.Value[1]) : char.ToLower(m.Value[1]))
- );
- }
- /// <summary>
- /// Converts given PascalCase/camelCase string to sentence (by splitting words by space).
- /// Example: "ThisIsSampleSentence" is converted to "This is a sample sentence".
- /// </summary>
- /// <param name="str">String to convert.</param>
- /// <param name="culture">An object that supplies culture-specific casing rules.</param>
- public static string ToSentenceCase(this string str, CultureInfo culture)
- {
- if (string.IsNullOrWhiteSpace(str))
- {
- return str;
- }
- return Regex.Replace(str, "[a-z][A-Z]", m => m.Value[0] + " " + char.ToLower(m.Value[1], culture));
- }
- /// <summary>
- /// Converts string to enum value.
- /// </summary>
- /// <typeparam name="T">Type of enum</typeparam>
- /// <param name="value">String value to convert</param>
- /// <returns>Returns enum object</returns>
- public static T ToEnum<T>(this string value)
- where T : struct
- {
- if (value == null)
- {
- throw new ArgumentNullException(nameof(value));
- }
- return (T)Enum.Parse(typeof(T), value);
- }
- /// <summary>
- /// Converts string to enum value.
- /// </summary>
- /// <typeparam name="T">Type of enum</typeparam>
- /// <param name="value">String value to convert</param>
- /// <param name="ignoreCase">Ignore case</param>
- /// <returns>Returns enum object</returns>
- public static T ToEnum<T>(this string value, bool ignoreCase)
- where T : struct
- {
- if (value == null)
- {
- throw new ArgumentNullException(nameof(value));
- }
- return (T)Enum.Parse(typeof(T), value, ignoreCase);
- }
- public static string ToMd5(this string str)
- {
- using (var md5 = MD5.Create())
- {
- var inputBytes = Encoding.UTF8.GetBytes(str);
- var hashBytes = md5.ComputeHash(inputBytes);
- var sb = new StringBuilder();
- foreach (var hashByte in hashBytes)
- {
- sb.Append(hashByte.ToString("X2"));
- }
- return sb.ToString();
- }
- }
- /// <summary>
- /// Converts camelCase string to PascalCase string.
- /// </summary>
- /// <param name="str">String to convert</param>
- /// <param name="invariantCulture">Invariant culture</param>
- /// <returns>PascalCase of the string</returns>
- public static string ToPascalCase(this string str, bool invariantCulture = true)
- {
- if (string.IsNullOrWhiteSpace(str))
- {
- return str;
- }
- if (str.Length == 1)
- {
- return invariantCulture ? str.ToUpperInvariant(): str.ToUpper();
- }
- return (invariantCulture ? char.ToUpperInvariant(str[0]) : char.ToUpper(str[0])) + str.Substring(1);
- }
- /// <summary>
- /// Converts camelCase string to PascalCase string in specified culture.
- /// </summary>
- /// <param name="str">String to convert</param>
- /// <param name="culture">An object that supplies culture-specific casing rules</param>
- /// <returns>PascalCase of the string</returns>
- public static string ToPascalCase(this string str, CultureInfo culture)
- {
- if (string.IsNullOrWhiteSpace(str))
- {
- return str;
- }
- if (str.Length == 1)
- {
- return str.ToUpper(culture);
- }
- return char.ToUpper(str[0], culture) + str.Substring(1);
- }
- /// <summary>
- /// Gets a substring of a string from beginning of the string if it exceeds maximum length.
- /// </summary>
- /// <exception cref="ArgumentNullException">Thrown if <paramref name="str"/> is null</exception>
- public static string Truncate(this string str, int maxLength)
- {
- if (str == null)
- {
- return null;
- }
- if (str.Length <= maxLength)
- {
- return str;
- }
- return str.Left(maxLength);
- }
- /// <summary>
- /// Gets a substring of a string from beginning of the string if it exceeds maximum length.
- /// It adds a "..." postfix to end of the string if it's truncated.
- /// Returning string can not be longer than maxLength.
- /// </summary>
- /// <exception cref="ArgumentNullException">Thrown if <paramref name="str"/> is null</exception>
- public static string TruncateWithPostfix(this string str, int maxLength)
- {
- return TruncateWithPostfix(str, maxLength, "...");
- }
- /// <summary>
- /// Gets a substring of a string from beginning of the string if it exceeds maximum length.
- /// It adds given <paramref name="postfix"/> to end of the string if it's truncated.
- /// Returning string can not be longer than maxLength.
- /// </summary>
- /// <exception cref="ArgumentNullException">Thrown if <paramref name="str"/> is null</exception>
- public static string TruncateWithPostfix(this string str, int maxLength, string postfix)
- {
- if (str == null)
- {
- return null;
- }
- if (str == string.Empty || maxLength == 0)
- {
- return string.Empty;
- }
- if (str.Length <= maxLength)
- {
- return str;
- }
- if (maxLength <= postfix.Length)
- {
- return postfix.Left(maxLength);
- }
- return str.Left(maxLength - postfix.Length) + postfix;
- }
- }
- }
|