using Newtonsoft.Json.Linq; using System; using System.Text; using System.Text.RegularExpressions; using Znyc.Cloudcar.Admin.Commons.Enums; namespace Znyc.Cloudcar.Admin.Commons.Helpers { /// /// 字符串帮助类 /// public class StringHelper { private static readonly char[] _constant = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; /// /// 生成随机字符串,默认32位 /// /// 随机数长度 /// public static string GenerateRandom(int length = 32) { StringBuilder newRandom = new StringBuilder(); Random rd = new Random(); for (int i = 0; i < length; i++) { newRandom.Append(_constant[rd.Next(_constant.Length)]); } return newRandom.ToString(); } /// /// 生成随机字符串,只包含数字 /// /// /// public static string GenerateRandomNumber(int length = 6) { StringBuilder newRandom = new StringBuilder(); Random rd = new Random(); for (int i = 0; i < length; i++) { newRandom.Append(_constant[rd.Next(10)]); } return newRandom.ToString(); } /// /// /// /// /// public static string Format(string str, object obj) { if (string.IsNullOrEmpty(str)) { return str; } string s = str; if (obj.GetType().Name == "JObject") { foreach (System.Collections.Generic.KeyValuePair item in (JObject)obj) { string k = item.Key; string v = item.Value.ToString(); s = Regex.Replace(s, "\\{" + k + "\\}", v, RegexOptions.IgnoreCase); } } else { foreach (System.Reflection.PropertyInfo p in obj.GetType().GetProperties()) { string xx = p.Name; string yy = p.GetValue(obj).ToString(); s = Regex.Replace(s, "\\{" + xx + "\\}", yy, RegexOptions.IgnoreCase); } } return s; } /// /// 隐藏手机号 /// /// /// public static string ConvertPhoneNo(string Phone) { return Regex.Replace(Phone, "(\\d{3})\\d{4}(\\d{4})", "$1****$2"); } /// /// 隐藏身份证号 /// /// /// public static string ConvertIdCard(string idCard) { return Regex.Replace(idCard, "(\\d{6})\\d{8}(\\w{4})", "$1********$2"); } /// /// 生成流水号 /// /// /// /// /// public static string GetSerialNumber(ProductTypeEnum productType, long IndustryId, long JobId) { return DateTime.Now.ToString("yyyyMMddhhmmss"); // + productType.ToInt() + IndustryId + JobId; } /// /// /// /// public static string ChineseMainlandForPhone(string phone) { return string.Format("+86{0}", phone); } /// /// 计算年龄 /// /// /// public static int? GetAgeByBirthDate(DateTime? birthDate) { int? age = 0; if (!birthDate.ToString().Equals("0001/1/1 0:00:00")) { DateTime now = DateTime.Now; age = now.Year - birthDate?.Year; if (now.Month < birthDate?.Month || now.Month == birthDate?.Month && now.Day < birthDate?.Day) { age--; } } return age < 0 ? 0 : age; } /// /// 计算百分比 /// /// 除数 /// 被除数 /// public static decimal GetPercent(decimal divisor, decimal dividend) { if (divisor == 0 || dividend == 0) { return Convert.ToDecimal(0); } return Math.Floor(Math.Round(decimal.Parse((divisor / dividend).ToString("0.000")), 2) * 100); } } }