StringUtil

164 阅读2分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路

   /// <summary>
        /// json格式的字符串转为阿里巴巴IconFont
        /// </summary>
        /// <param name="json">json格式的字符串</param>
        /// <returns></returns>
        public static IconFont ToALiIconFont(this string json)
        {
            return JsonConvert.DeserializeObject<IconFont>(json.Replace("@class", "class").Replace("#text", "text"));
        }

        /// <summary>
        /// 非空或null检查
        /// </summary>
        /// <param name="param">参数</param>
        public static void NotNullOrEmpty(this string param)
        {
            param.NotNull();
            if (param is null)
            {
                throw new ArgumentNullException(nameof(param));
            }
        }

        /// <summary>
        /// 判断一个字符串是否可以转为正数或0
        /// </summary>
        /// <param name="str">字符串实例</param>
        /// <returns></returns>
        public static bool IsPositiveNumber(this string str)
        {
            return Regex.IsMatch(str, @"^(\d*[.]?\d*)$");
        }

        /// <summary>
        /// 判断一个字符串是否可以转为负数
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsNegativeNumber(this string str)
        {
            return Regex.IsMatch(str, @"^(-\d*[.]?\d*)$");
        }

        /// <summary>
        /// 判断一个字符串是否可以转为数字
        /// </summary>
        /// <param name="str">字符串实例</param>
        /// <returns></returns>
        public static bool IsNumber(this string str)
        {
            return Regex.IsMatch(str, @"^(-?\d*[.]?\d*)$");
        }

        /// <summary>
        /// json格式字符串转字典扩展方法
        /// </summary>
        /// <param name="json">json格式字符串</param>
        /// <returns></returns>
        public static Dictionary<string, object> ToDictionary(this string json)
        {
            var res = new Dictionary<string, object>();
            try
            {
                JObject jsonObj = JsonConvert.DeserializeObject(json) as JObject;
                foreach (var p in jsonObj.Properties())
                {
                    if (jsonObj[p.Name].GetType() == typeof(JObject))
                    {
                        res.Add(p.Name, jsonObj[p.Name].ToDictionary());
                    }
                    else if (jsonObj[p.Name].GetType() == typeof(JArray))
                    {
                        var jsonArr = JsonConvert.DeserializeObject(jsonObj[p.Name].ToString()) as JArray;
                        var dic = new Dictionary<string, object>();
                        for (int i = 0; i < jsonArr.Count; i++)
                        {
                            dic.Add($"{p.Name}{i}", jsonArr[i].ToDictionary());
                        }
                        res.Add(p.Name, dic);
                    }
                    else if (jsonObj[p.Name].GetType() == typeof(JValue))
                    {
                        res.Add(p.Name, jsonObj[p.Name].Value<string>());
                    }
                }
            }
            catch (Exception)
            {
                res.Add($"NotJson{DateTime.Now:yyyyMMddHHmmssfff}", json);
            }
            return res;
        }

        /// <summary>
        /// 汉字转全拼
        /// </summary>
        /// <param name="chinese">中文汉字</param>
        /// <returns></returns>
        public static string ToAllSpell(this string chinese)
        {
            try
            {
                if (chinese.Length != 0)
                {
                    StringBuilder fullSpell = new StringBuilder();
                    for (int i = 0; i < chinese.Length; i++)
                    {
                        var chr = chinese[i];
                        var temp = GetSpell(chr).ToLower();
                        fullSpell.Append(temp.Substring(0, 1).ToUpper() + temp.Substring(1));
                    }
                    return fullSpell.ToString();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("全拼转化出错!" + e.Message);
            }

            return string.Empty;
        }

        /// <summary>
        /// 汉字转首字母
        /// </summary>
        /// <param name="strChinese"></param>
        /// <returns></returns>
        public static string GetFirstSpell(this string strChinese)
        {
            //NPinyin.Pinyin.GetInitials(strChinese)  有Bug  洺无法识别
            //return NPinyin.Pinyin.GetInitials(strChinese);

            try
            {
                if (strChinese.Length != 0)
                {
                    StringBuilder fullSpell = new StringBuilder();
                    for (int i = 0; i < strChinese.Length; i++)
                    {
                        var chr = strChinese[i];
                        fullSpell.Append(GetSpell(chr)[0]);
                    }

                    return fullSpell.ToString().ToUpper();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("首字母转化出错!" + e.Message);
            }

            return string.Empty;
        }

        /// <summary>
        /// 单词首字母转大写,其他字母转小写
        /// </summary>
        /// <param name="str"></param>
        public static string ToFirstCharUpper(this string str)
        {
            try
            {
                return str.Length == 1 ? str.ToUpper() : str[..1].ToUpper() + str[1..].ToLower();
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 字符串单词首字母转大写,其他字母转小写
        /// 单词之间没有分隔符
        /// </summary>
        /// <param name="str">字符串</param>
        /// <param name="separator">分隔符</param>
        /// <returns></returns>
        public static string ToFirstCharUpperWithoutSeparator(this string str, string separator)
        {
            return ToFirstCharUpperWithSeparator(str, separator);
        }

        /// <summary>
        /// 字符串单词首字母转大写,其他字母转小写
        /// 单词之间没有分隔符
        /// </summary>
        /// <param name="str">字符串</param>
        /// <param name="separators">分隔符</param>
        /// <returns></returns>
        public static string ToFirstCharUpperWithoutSeparator(this string str, ICollection<string> separators)
        {
            return ToFirstCharUpperWithSeparator(str, separators);
        }

        /// <summary>
        /// 字符串单词首字母转大写,其他字母转小写
        /// 单词之间有分隔符
        /// </summary>
        /// <param name="str">字符串</param>
        /// <param name="oldSeparator">原来的分隔符</param>
        /// <param name="newSeparator">新的分隔符</param>
        /// <returns></returns>
        public static string ToFirstCharUpperWithSeparator(this string str, string oldSeparator, string newSeparator = "")
        {
            try
            {
                var sp = str.Split(oldSeparator, StringSplitOptions.RemoveEmptyEntries);

                var sb = new string[sp.Length];
                for (int i = 0; i < sp.Length; i++)
                {
                    sb[i] = sp[i].ToFirstCharUpper();
                }
                return string.Join(newSeparator, sb);
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 字符串单词首字母转大写,其他字母转小写
        /// 单词之间有分隔符
        /// </summary>
        /// <param name="str">字符串</param>
        /// <param name="oldSeparators">原来的分隔符</param>
        /// <param name="newSeparator">新的分隔符</param>
        /// <returns></returns>
        public static string ToFirstCharUpperWithSeparator(this string str, ICollection<string> oldSeparators, string newSeparator = "")
        {
            try
            {
                var sp = str.Split(oldSeparators.ToArray(), StringSplitOptions.RemoveEmptyEntries);

                var sb = new string[sp.Length];
                for (int i = 0; i < sp.Length; i++)
                {
                    sb[i] = sp[i].ToFirstCharUpper();
                }
                return string.Join(newSeparator, sb);
            }
            catch (Exception)
            {
                throw;
            }
        }

        private static string GetSpell(char chr)
        {
            var coverchr = NPinyin.Pinyin.GetPinyin(chr);
            bool isChineses = ChineseChar.IsValidChar(coverchr[0]);
            if (isChineses)
            {
                ChineseChar chineseChar = new ChineseChar(coverchr[0]);
                foreach (string value in chineseChar.Pinyins)
                {
                    if (!string.IsNullOrEmpty(value))
                    {
                        return value.Remove(value.Length - 1, 1);
                    }
                }
            }
            return coverchr;
        }