123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617 |
- using Ips.Library.Basic;
- using System;
- using System.Collections.Generic;
- using System.Globalization;
- using System.Security.Cryptography;
- using System.Text;
- using System.Text.Encodings.Web;
- using System.Text.Json.Serialization;
- using System.Text.Json;
- using System.Text.RegularExpressions;
- using System.Text.Unicode;
- using Newtonsoft.Json;
- using System.Net;
- //namespace Ips.Library.Basic
- //{
- public static class StringExtensions
- {
- public static string[] ToStrArray(this string @this)
- {
- return new string[1]
- {
- @this
- };
- }
- public static List<string> ToStrList(this string @this)
- {
- return new List<string>
- {
- @this
- };
- }
- /// <summary>
- /// 使用Newtonsoft Json将string转换为对象
- /// </summary>
- /// <param name="this"></param>
- /// <returns></returns>
- public static T ToObj<T>(this string @this)
- {
- JsonSerializerSettings jsonSettings = new JsonSerializerSettings
- {
- DateFormatString = "yyyy-MM-dd HH:mm:ss",
- };
- return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(@this, jsonSettings);
- }
- /// <summary>
- /// 为url字符串添加后缀
- /// </summary>
- /// <param name="this"></param>
- /// <param name="suffix"></param>
- /// <returns></returns>
- public static string AppendUrlSuffix(this string @this, string suffix)
- {
- if (suffix.StartsWith("/"))
- suffix = suffix.Substring(1);
- if (@this.EndsWith("/"))
- return $"{@this}{suffix}";
- else
- return $"{@this}/{suffix}";
- }
- /// <summary>
- /// 获取url中的端口
- /// </summary>
- /// <param name="this"></param>
- /// <returns></returns>
- public static int GetUrlPort(this string @this)
- {
- try
- {
- bool isHttps = @this.ToLower().StartsWith("https");
- var newStr = @this.ToLower().Replace("https://", "").Replace("http://", "");
- var idx1 = newStr.IndexOf(":");
- if (idx1 < 0)
- {
- if (isHttps)
- return 443;
- else
- return 80;
- }
- var idx2 = newStr.IndexOf("/");
- var str = newStr.Substring(idx1 + 1, idx2 - idx1 - 1);
- return Convert.ToInt32(str);
- }
- catch
- {
- return 0;
- }
- }
- public static string EnsureEndsWith(this string str, char c, StringComparison comparisonType = StringComparison.Ordinal)
- {
- if (str.EndsWith(c.ToString(), comparisonType))
- {
- return str;
- }
- return str + c;
- }
- public static string EnsureStartsWith(this string str, char c, StringComparison comparisonType = StringComparison.Ordinal)
- {
- if (str.StartsWith(c.ToString(), comparisonType))
- {
- return str;
- }
- return c + str;
- }
- public static bool IsNullOrEmpty(this string @this)
- {
- return String.IsNullOrEmpty(@this);
- }
- public static bool IsNotNullOrEmpty(this string @this)
- {
- return !String.IsNullOrEmpty(@this);
- }
- public static bool IsNullOrWhitespace(this string @this)
- {
- return String.IsNullOrWhiteSpace(@this);
- }
- public static bool IsNotNullOrWhitespace(this string @this)
- {
- return !String.IsNullOrWhiteSpace(@this);
- }
- public static string IfNullOrEmpty(this string @this, string defaultVal)
- {
- return String.IsNullOrEmpty(@this) ? defaultVal : @this;
- }
- public static string IfNullOrWhitespace(this string @this, string defaultVal)
- {
- return String.IsNullOrWhiteSpace(@this) ? defaultVal : @this;
- }
- public static string ClearWhitespace(this string @this)
- {
- if (String.IsNullOrWhiteSpace(@this)) return String.Empty;
- return @this.Replace(" ", String.Empty);
- }
- public static string Left(this string @this, int length)
- {
- if (String.IsNullOrEmpty(@this)) return String.Empty;
- return @this.Length < length ? @this : @this.Substring(0, length);
- }
- public static string Rigth(this string @this, int length)
- {
- if (String.IsNullOrEmpty(@this)) return String.Empty;
- return @this.Length < length ? @this : @this.Substring(@this.Length - length);
- }
- public static string TrimToMaxLength(this string @this, int maxLength, string suffix = "")
- {
- return ((@this == null || @this.Length <= maxLength) ? @this : String.Concat(@this.Substring(0, maxLength), suffix));
- }
- public static T To<T>(this string @this)
- {
- return To(@this, default(T));
- }
- public static T To<T>(this string @this, T defaultValue)
- {
- if (String.IsNullOrWhiteSpace(@this))
- return defaultValue;
- T retVal = defaultValue;
- try
- {
- //获取要转换的目标类型
- Type targetType = typeof(T);
- //对 Guid 类型的值进行单独处理
- if (targetType == typeof(Guid))
- retVal = (T)((object)(new Guid(@this)));
- //对 Enum 类型的值进行单独处理
- else if (targetType.BaseType == typeof(Enum))
- retVal = (T)Enum.Parse(targetType, @this);
- else
- retVal = (T)Convert.ChangeType(@this, targetType);
- }
- catch { }
- return retVal;
- }
- public static string NormalizeLineEndings(this string str)
- {
- return str.Replace("\r\n", "\n").Replace("\r", "\n").Replace("\n", Environment.NewLine);
- }
- public static int NthIndexOf(this string str, char c, int n)
- {
- var count = 0;
- for (var i = 0; i < str.Length; i++)
- {
- if (str[i] != c)
- {
- continue;
- }
- if ((++count) == n)
- {
- return i;
- }
- }
- return -1;
- }
- public static string RemovePostFix(this string str, params string[] postFixes)
- {
- return str.RemovePostFix(StringComparison.Ordinal, postFixes);
- }
- public static string RemovePostFix(this string str, StringComparison comparisonType, params string[] postFixes)
- {
- if (str.IsNullOrEmpty())
- {
- return str;
- }
- if (postFixes.IsNullOrEmpty())
- {
- return str;
- }
- foreach (var postFix in postFixes)
- {
- if (str.EndsWith(postFix, comparisonType))
- {
- return str.Left(str.Length - postFix.Length);
- }
- }
- return str;
- }
- public static string RemovePreFix(this string str, params string[] preFixes)
- {
- return str.RemovePreFix(StringComparison.Ordinal, preFixes);
- }
- public static string RemovePreFix(this string str, StringComparison comparisonType, params string[] preFixes)
- {
- if (str.IsNullOrEmpty())
- {
- return str;
- }
- if (preFixes.IsNullOrEmpty())
- {
- return str;
- }
- foreach (var preFix in preFixes)
- {
- if (str.StartsWith(preFix, comparisonType))
- {
- return str.Right(str.Length - preFix.Length);
- }
- }
- return str;
- }
- public static string ReplaceFirst(this string str, string search, string replace, StringComparison comparisonType = StringComparison.Ordinal)
- {
- var pos = str.IndexOf(search, comparisonType);
- if (pos < 0)
- {
- return str;
- }
- return str.Substring(0, pos) + replace + str.Substring(pos + search.Length);
- }
- public static string Right(this string str, int len)
- {
- 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);
- }
- public static string[] Split(this string str, string separator)
- {
- return str.Split(new[] { separator }, StringSplitOptions.None);
- }
- public static string[] Split(this string str, string separator, StringSplitOptions options)
- {
- return str.Split(new[] { separator }, options);
- }
- public static string[] SplitToLines(this string str)
- {
- return str.Split(Environment.NewLine);
- }
- public static string[] SplitToLines(this string str, StringSplitOptions options)
- {
- return str.Split(Environment.NewLine, options);
- }
- public static string ToCamelCase(this string str, bool useCurrentCulture = false, bool handleAbbreviations = false)
- {
- if (string.IsNullOrWhiteSpace(str))
- {
- return str;
- }
- if (str.Length == 1)
- {
- return useCurrentCulture ? str.ToLower() : str.ToLowerInvariant();
- }
- if (handleAbbreviations && IsAllUpperCase(str))
- {
- return useCurrentCulture ? str.ToLower() : str.ToLowerInvariant();
- }
- return (useCurrentCulture ? char.ToLower(str[0]) : char.ToLowerInvariant(str[0])) + str.Substring(1);
- }
- public static string ToSentenceCase(this string str, bool useCurrentCulture = false)
- {
- if (string.IsNullOrWhiteSpace(str))
- {
- return str;
- }
- return useCurrentCulture
- ? Regex.Replace(str, "[a-z][A-Z]", m => m.Value[0] + " " + char.ToLower(m.Value[1]))
- : Regex.Replace(str, "[a-z][A-Z]", m => m.Value[0] + " " + char.ToLowerInvariant(m.Value[1]));
- }
- public static string ToKebabCase(this string str, bool useCurrentCulture = false)
- {
- if (string.IsNullOrWhiteSpace(str))
- {
- return str;
- }
- str = str.ToCamelCase();
- return useCurrentCulture
- ? Regex.Replace(str, "[a-z][A-Z]", m => m.Value[0] + "-" + char.ToLower(m.Value[1]))
- : Regex.Replace(str, "[a-z][A-Z]", m => m.Value[0] + "-" + char.ToLowerInvariant(m.Value[1]));
- }
- public static string ToSnakeCase(this string str)
- {
- if (string.IsNullOrWhiteSpace(str))
- {
- return str;
- }
- var builder = new StringBuilder(str.Length + Math.Min(2, str.Length / 5));
- var previousCategory = default(UnicodeCategory?);
- for (var currentIndex = 0; currentIndex < str.Length; currentIndex++)
- {
- var currentChar = str[currentIndex];
- if (currentChar == '_')
- {
- builder.Append('_');
- previousCategory = null;
- continue;
- }
- var currentCategory = char.GetUnicodeCategory(currentChar);
- switch (currentCategory)
- {
- case UnicodeCategory.UppercaseLetter:
- case UnicodeCategory.TitlecaseLetter:
- if (previousCategory == UnicodeCategory.SpaceSeparator ||
- previousCategory == UnicodeCategory.LowercaseLetter ||
- previousCategory != UnicodeCategory.DecimalDigitNumber &&
- previousCategory != null &&
- currentIndex > 0 &&
- currentIndex + 1 < str.Length &&
- char.IsLower(str[currentIndex + 1]))
- {
- builder.Append('_');
- }
- currentChar = char.ToLower(currentChar);
- break;
- case UnicodeCategory.LowercaseLetter:
- case UnicodeCategory.DecimalDigitNumber:
- if (previousCategory == UnicodeCategory.SpaceSeparator)
- {
- builder.Append('_');
- }
- break;
- default:
- if (previousCategory != null)
- {
- previousCategory = UnicodeCategory.SpaceSeparator;
- }
- continue;
- }
- builder.Append(currentChar);
- previousCategory = currentCategory;
- }
- return builder.ToString();
- }
- public static T ToEnum<T>(this string value)
- where T : struct
- {
- return (T)Enum.Parse(typeof(T), value);
- }
- public static T ToEnum<T>(this string value, bool ignoreCase)
- where T : struct
- {
- 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();
- }
- }
- public static string ToPascalCase(this string str, bool useCurrentCulture = false)
- {
- if (string.IsNullOrWhiteSpace(str))
- {
- return str;
- }
- if (str.Length == 1)
- {
- return useCurrentCulture ? str.ToUpper() : str.ToUpperInvariant();
- }
- return (useCurrentCulture ? char.ToUpper(str[0]) : char.ToUpperInvariant(str[0])) + str.Substring(1);
- }
- public static string Truncate(this string str, int maxLength)
- {
- if (str == null)
- {
- return null;
- }
- if (str.Length <= maxLength)
- {
- return str;
- }
- return str.Left(maxLength);
- }
- public static string TruncateFromBeginning(this string str, int maxLength)
- {
- if (str == null)
- {
- return null;
- }
- if (str.Length <= maxLength)
- {
- return str;
- }
- return str.Right(maxLength);
- }
- public static string TruncateWithPostfix(this string str, int maxLength)
- {
- return TruncateWithPostfix(str, maxLength, "...");
- }
- 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;
- }
- public static byte[] GetBytes(this string str)
- {
- return str.GetBytes(Encoding.UTF8);
- }
- public static byte[] GetBytes(this string str, Encoding encoding)
- {
- return encoding.GetBytes(str);
- }
- private static bool IsAllUpperCase(string input)
- {
- for (int i = 0; i < input.Length; i++)
- {
- if (Char.IsLetter(input[i]) && !Char.IsUpper(input[i]))
- {
- return false;
- }
- }
- return true;
- }
- public static byte[] ToBytes(this string input, int byteCount = 0, Encoding encoding = null)
- {
- encoding = encoding ?? Encoding.UTF8;
- input = input ?? "";
- var strBuffer = encoding.GetBytes(input);
- if (byteCount == 0) return strBuffer;
- var buffer = new byte[byteCount];
- Array.Copy(strBuffer, 0, buffer, 0, Math.Min(strBuffer.Length, buffer.Length));
- return buffer;
- }
- public static IPAddress ToIpAddress(this string strIP)
- {
- return IPAddress.Parse(strIP);
- }
- /// <summary>
- /// 字符串是否包含字符集合中的某个元素
- /// </summary>
- /// <param name="str"></param>
- /// <param name="values">字符串数组</param>
- /// <returns></returns>
- public static bool ContainsOne(this string str, IEnumerable<string> values)
- {
- if (str == null) return false;
- foreach (var item in values)
- {
- if (str.Contains(item)) return true;
- }
- return false;
- }
- /// <summary>
- /// 字符串是否包含字符集合中的所有元素
- /// </summary>
- /// <param name="str"></param>
- /// <param name="values">字符串数组</param>
- /// <returns></returns>
- public static bool ContainsAll(this string str, IEnumerable<string> values)
- {
- if (str == null) return false;
- foreach (var item in values)
- {
- if (!str.Contains(item)) return false;
- }
- return true;
- }
- /// <summary>
- /// 判断字符串是否为null或空白字符
- /// </summary>
- /// <param name="s"></param>
- /// <returns></returns>
- public static bool IsNull(this string s)
- {
- return string.IsNullOrWhiteSpace(s);
- }
- /// <summary>
- /// 判断字符串是否不为null或空白字符
- /// </summary>
- /// <param name="s"></param>
- /// <returns></returns>
- public static bool NotNull(this string s)
- {
- return !string.IsNullOrWhiteSpace(s);
- }
- }
- //}
|