C#个人常用标准库 > StringTool


提供一些基本的字符串操作方法


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;

namespace ZmjTool
{
    /// <summary>
    /// 提供一些基本的字符串操作方法
    /// </summary>
    public static class StringTool
    {
        /// <summary>
        /// 正则表达式匹配邮箱时的正则表达式字符串
        /// </summary>
        public static readonly string MailRegexMark = @"^\w(\w+)@(\w+)\.([A-Za-z]{2,3})(\.?)([A-Za-z]{0,2})$";
        /// <summary>
        /// 获取指定长度个字符串,ascii字符串,包含a-z及0-9
        /// </summary>
        /// <param name="len"></param>
        /// <returns></returns>
        public static string GetRandString(int len)
        {
            var rd = new Random(DateTime.Now.Millisecond);
            var ids = new char[len - 10];
            for (int i = 0; i < len; i++) ids[i] = (char)rd.NextRandChar();
            return new string(ids);
        }
        /// <summary>
        /// 获取下一个rand字符,a-z大小写及0-9
        /// </summary>
        /// <param name="rd"></param>
        /// <returns></returns>
        public static int NextRandChar(this Random rd)
        {
            rd = rd ?? new Random(DateTime.Now.Millisecond);
            int co = rd.Next(0, 3);
            return co == 0 ? rd.Next('0', '9' + 1) : co == 1 ? rd.Next('a', 'z' + 1) : rd.Next('A', 'Z' + 1);
        }
        /// <summary>
        /// 常用的断句用的符号
        /// </summary>
        public static readonly string CommonBrokenSymbols = " ,.\'‘“\",。;;、/\\??、~~!@&#$*++--_—|";
        /// <summary>
        /// 只支持标点符号断句
        /// </summary>
        /// <param name="kw"></param>
        /// <returns></returns>
        public static string[] SplitKeyword(this string kw) => kw?.Split(CommonBrokenSymbols.ToArray(), StringSplitOptions.RemoveEmptyEntries) ?? Array.Empty<string>();
        /// <summary>
        /// 支持英文大小写断句
        /// </summary>
        /// <param name="kw"></param>
        /// <param name="take"></param>
        /// <returns></returns>
        public static string[] SplitCaseWord(this string kw, int take = 0)
        {
            var kws = string.IsNullOrWhiteSpace(kw) ? Array.Empty<string>() : kw.Split(CommonBrokenSymbols.ToArray(), StringSplitOptions.RemoveEmptyEntries);
            var aks = new List<string>();
            foreach (var item in kws) SplitCaseWord(item, aks);
            take = take < 3 ? aks.Count : take;
            return aks.Take(take).ToArray();
        }
        /// <summary>
        /// 按照英文大小写拆分单词
        /// </summary>
        /// <param name="wd"></param>
        /// <param name="lst"></param>
        /// <returns></returns>
        public static void SplitCaseWord(this string wd, List<string> lst)
        {
            if (wd.Length < 1) return;
            var isUp = wd[0] < 'a';
            var st = 0;
            int ed;
            do
            {
                ed = IndexOfChar(wd, c => isUp ^ (c < 'a'), st);
                if (ed < 0)
                {//最后的一个单词
                    lst.Add(wd.Substring(st));
                    break;
                }//期间的一些单词
                lst.Add(wd.Substring(st, ed - st + 1));
                st += ed;
                isUp = wd[st] < 'a';
            } while (ed > 0);
        }
        /// <summary>
        /// 获取级别相关的字符串
        /// </summary>
        /// <param name="level"></param>
        /// <returns></returns>
        public static string GetLevelStr(this int level)//string levelstr)
        {
            //int level = int.Parse(levelstr);
            if (level >= 100) return "站长";
            if (level >= 90) return "高级管理V" + (level - 89);
            if (level >= 80) return "普通管理V" + (level - 79);
            if (level >= 40) return "高级Vip会员V" + (level - 39);
            if (level >= 20) return "Vip会员V" + (level - 19);
            return "普通会员V" + (level + 1);
        }
        /// <summary>
        /// 更具离线时间获取离线状态字符串
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static string GetOffStr(this DateTime? dt)//string lastActiveTimestr)
        {
            if (!dt.HasValue) return "未知";
            TimeSpan ts = DateTime.Now - dt.Value;
            if (ts.TotalMinutes < 30) return "在线";
            if (ts.TotalHours < 1) return "刚刚离线";
            if (ts.TotalHours < 24) return "离线" + ts.Hours + "个小时";
            if (ts.TotalDays < 30) return "离线" + ts.Days + "天";
            if (ts.TotalDays < 365) return "离线" + ((int)(ts.TotalDays / 30)) + "个月";
            return "离线" + ((int)(ts.TotalDays / 365)) + "年";
        }
        /// <summary>
        /// 将文件的大小表示为字符串,且使用缩进转换
        /// </summary>
        /// <param name="sz"></param>
        /// <returns></returns>
        public static string GetFileSizeStr(this long? sz)
        {
            if (!sz.HasValue || sz < 0) return "未知";
            if (sz.Value < 1000) return sz.Value + "B";
            if (sz.Value < 1000000) return (sz.Value / 1000f).ToString("0.##") + "KB";
            if (sz.Value < 1000000000) return (sz.Value / 1000000f).ToString("0.##") + "MB";
            return (sz.Value / 1000000000f).ToString("0.##") + "GB";
        }
        /// <summary>
        /// 数组合并
        /// </summary>
        /// <param name="array"></param>
        /// <returns></returns>
        public static string GetString(this IEnumerable<string> array)
        {
            return string.Join("", array);
        }
        /// <summary>
        /// 从一个url中分离出下载文件时用的基本url
        /// </summary>
        /// <param name="url"></param>
        /// <param name="name">输出从中获取的名称</param>
        /// <returns></returns>
        //public static string GetBaseUrl(string url, out string first, out string last)
        //{
        //    first = "";
        //    last = "";
        //    int i = url.LastIndexOf('/');
        //    if ((i + 1) >= url.Length) return url;//当url以/结尾时
        //    string fm = url.Substring(i + 1, url.Length - i - 1);
        //    if (fm.LastIndexOf('.') > 0)
        //    {
        //        first = fm.Substring(0, fm.LastIndexOf('.'));//这里是xx
        //        last = fm.Substring(fm.LastIndexOf('.'));//这里是.m3u8
        //        return url.Substring(0, i + 1);//典型情况.../xx.m3u8
        //    }
        //    first = fm;
        //    return url + "/";//未知情况
        //}
        /// <summary>
        /// 判断某个字符串中是否存指定的特殊字符特殊字符
        /// </summary>
        /// <param name="str"></param>
        /// <param name="regEx">指定需要检测的特殊字符</param>
        /// <returns></returns>
        public static bool HaveOtherChar(this string str, string regEx = ":*?<>|\"'")
        {
            //string regEx = @"[ _.`~!@#$%^&*()+=|{}':;',\\[\\]<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]|\n|\r|\t";
            //return Regex.IsMatch(str, @"[\u4e00-\u9fa5]");
            //if ((str == null) || (regEx == null)) throw new ArgumentNullException("str or regEx", "不能为空");
            return (str.IndexOfAny(regEx.ToCharArray()) >= 0);
        }
        /// <summary>
        /// 从指定位置向后查找符合条件的字符
        /// </summary>
        /// <param name="str"></param>
        /// <param name="func"></param>
        /// <param name="st"></param>
        /// <returns></returns>
        public static int IndexOfChar(this string str, Func<char, bool> func, int st = 0)
        {
            for (int i = st; i < str.Length; i++)
            {
                if (func.Invoke(str[i])) return i;
            }
            return -1;
        }
        /// <summary>
        /// 查看字符串是否全是数字
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static bool IsAllNum(this string s)
        {
            if (string.IsNullOrEmpty(s)) return false;
            return s.All(c => c.IsNumber());
        }
        /// <summary>
        /// 验证一个字符是否是字符数字或者指定的字符集之一
        /// </summary>
        /// <param name="c"></param>
        /// <param name="oc"></param>
        /// <returns></returns>
        public static bool IsCharOrNumberAnd(this char c, char[] oc)
        {
            return ((c <= 'z') && (c >= 'a')) || ((c <= 'Z') && (c >= 'A')) || ((c <= '9') && (c >= '0') || oc.Contains(c));
        }
        /// <summary>
        /// 验证字母或者数字
        /// </summary>
        /// <param name="c"></param>
        /// <returns></returns>
        public static bool IsCharOrNumber(this char c)
        {
            return ((c <= 'z') && (c >= 'a')) || ((c <= 'Z') && (c >= 'A')) || ((c <= '9') && (c >= '0'));
        }
        /// <summary>
        /// 判断一个字符是否是a-z,不分大小写
        /// </summary>
        /// <param name="c"></param>
        /// <returns></returns>
        public static bool IsAZChar(this char c)
        {
            return ((c <= 'z') && (c >= 'a')) || ((c <= 'Z') && (c >= 'A'));
        }
        /// <summary>
        /// 判断一个char是否是0-9
        /// </summary>
        /// <param name="c"></param>
        /// <returns></returns>
        public static bool IsNumber(this char c)
        {
            return (c <= '9') && (c >= '0');
        }
    }
}