C#常用工具类——字符串处理

  大家好,我是阿赵。
  在做Unity项目的时候,会用到C#脚本编写功能。其中字符串的处理经常会用到。这里我整理了一个工具类,里面包括了一些常用的功能,比如说一些常用的正则匹配、字符串格式化、切割字符串、版本对比等。

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;

    public class StringTools
    {
        static private StringTools _instance;

        public static StringTools Instance
        {
            get { 
                if(_instance==null)
                {
                    _instance = new StringTools();
                }
                return _instance;
            }
        }

    #region 正则匹配方法
    /// <summary>
    /// 获取第一个匹配
    /// </summary>
    /// <param name="str"></param>
    /// <param name="regexStr"></param>
    /// <returns></returns>
    static public string GetFirstMatch(string str, string regexStr)
    {
        if (string.IsNullOrEmpty(str) || string.IsNullOrEmpty(regexStr))
        {
            return null;
        }
        Match m = Regex.Match(str, regexStr);
        if (!string.IsNullOrEmpty(m.ToString()))
        {
            return m.ToString();
        }
        else
        {
            return null;
        }
    }
    /// <summary>
    /// 获取第一个匹配,返回match
    /// </summary>
    /// <param name="str"></param>
    /// <param name="regexStr"></param>
    /// <returns></returns>
    static public Match GetFirstMatchStruct(string str, string regexStr)
    {
        if (string.IsNullOrEmpty(str) || string.IsNullOrEmpty(regexStr))
        {
            return null;
        }
        Match m = Regex.Match(str, regexStr);
        if (!string.IsNullOrEmpty(m.ToString()))
        {
            return m;
        }
        else
        {
            return null;
        }
    }


    /// <summary>
    /// 获取所有匹配,返回string[]
    /// </summary>
    /// <param name="str"></param>
    /// <param name="regexStr"></param>
    /// <returns></returns>
    static public string[] GetAllMatchs(string str, string regexStr)
    {
        if (string.IsNullOrEmpty(str) || string.IsNullOrEmpty(regexStr))
        {
            return null;
        }
        MatchCollection mc = Regex.Matches(str, regexStr);
        if (mc.Count == 0)
        {
            return null;
        }
        string[] matchs = new string[mc.Count];
        for (int i = 0; i < mc.Count; i++)
        {
            matchs[i] = mc[i].Value.ToString();
        }
        return matchs;
    }
    /// <summary>
    /// 获取所有匹配,返回List<string>
    /// </summary>
    /// <param name="str"></param>
    /// <param name="regexStr"></param>
    /// <returns></returns>
    static public List<string> GetAllMatchs2(string str, string regexStr)
    {
        if (string.IsNullOrEmpty(str) || string.IsNullOrEmpty(regexStr))
        {
            return null;
        }
        MatchCollection mc = Regex.Matches(str, regexStr);
        if (mc.Count == 0)
        {
            return null;
        }
        List<string> matchs = new List<string>();
        for (int i = 0; i < mc.Count; i++)
        {
            matchs.Add(mc[i].Value.ToString());
        }
        return matchs;
    }

    /// <summary>
    /// 获取所有匹配,返回match
    /// </summary>
    /// <param name="str"></param>
    /// <param name="regexStr"></param>
    /// <returns></returns>
    static public Match[] GetAllMatchsStruct(string str, string regexStr)
    {
        if (string.IsNullOrEmpty(str) || string.IsNullOrEmpty(regexStr))
        {
            return null;
        }
        MatchCollection mc = Regex.Matches(str, regexStr);
        if (mc.Count == 0)
        {
            return null;
        }
        Match[] matchs = new Match[mc.Count];
        for (int i = 0; i < mc.Count; i++)
        {
            matchs[i] = mc[i];
        }
        return matchs;
    }
    #endregion

    #region 匹配字符串内容

    /// <summary>
    /// 判断是否是合法的IP地址
    /// </summary>
    /// <param name="ip"></param>
    /// <returns></returns>
    public static bool GetLegitimateIP(string ip)
    {
        if(string.IsNullOrEmpty(ip))
        {
            return false;
        }
        Regex rx = new Regex(@"((?:(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d))))");
        if (rx.IsMatch(ip))
        {
            return true;
        }
        return false;
    }


    /// <summary>
    /// 获取是否为纯数字
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    static public bool IsNumber(string expression)
    {
        string getIsNumber = @"^\-?[0-9]+(\.[0-9]*)?$";
        MatchCollection mc = Regex.Matches(expression, getIsNumber);
        if (mc.Count > 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    #endregion

    #region 处理字符串

    /// <summary>
    /// 格式化字符串,替代{数字}内容
    /// </summary>
    /// <param name="str"></param>
    /// <param name="args"></param>
    /// <returns></returns>
    static public string Format(string str, params object[] args)
        {
            string newStr = str;
            string rexStr = @"\{[0-9]+\}";
            MatchCollection mc = Regex.Matches(str, rexStr);
            if (mc.Count > 0)
            {
                for (int i = 0; i < mc.Count; i++)
                {
                    string subStr = "{" + i + "}";
                    if (i < args.Length)
                    {
                        Type t = args[i].GetType();
                        newStr = newStr.Replace(subStr, args[i].ToString());
                    }
                    else
                    {
                        newStr = newStr.Replace(subStr,"");
                    }

                }


            }
            return newStr;
        }

        
        /// <summary>
        /// 切割字符串,返回string[]
        /// </summary>
        /// <param name="str"></param>
        /// <param name="splitStr"></param>
        /// <returns></returns>
        static public string[] Split(string str,string splitStr)
        {
            if (string.IsNullOrEmpty(str) || string.IsNullOrEmpty(splitStr))
            {
                return null;
            }
            string[] newStrs = Regex.Split(str, splitStr);
            return newStrs;
        }
        /// <summary>
        /// 切割字符串,返回List<string>
        /// </summary>
        /// <param name="str"></param>
        /// <param name="splitStr"></param>
        /// <returns></returns>
        static public List<string> Split2(string str, string splitStr)
        {
            if (string.IsNullOrEmpty(str) || string.IsNullOrEmpty(splitStr))
            {
                return null;
            }
            string[] newStrs = Regex.Split(str, splitStr);
            List<string> strs = new List<string>();

            for(int i = 0;i<newStrs.Length;i++)
            {
                strs.Add(newStrs[i]);
            }
            return strs;
        }
        /// <summary>
        /// 切割字符串,返回数组
        /// </summary>
        /// <param name="str"></param>
        /// <param name="splitStr"></param>
        /// <returns></returns>
        static public string[] SplitStr(string str,char splitStr)
        {
            if (string.IsNullOrEmpty(str))
            {
                return null;
            }
            return str.Split(splitStr);
        }


        /// <summary>
        /// 去掉换行符
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        static public string RemoveReturn(string str)
        {
            return StringTools.Replace(str, "\r\n|\r|\n", "");
        }

        /// <summary>
        /// 用正则表达式替换字符串
        /// </summary>
        /// <param name="str"></param>
        /// <param name="str1"></param>
        /// <param name="str2"></param>
        /// <returns></returns>
        static public string Replace(string str,string str1,string str2)
        {
            if (string.IsNullOrEmpty(str) || string.IsNullOrEmpty(str1)||str2==null)
            {
                return null;
            }
            Regex rgx = new Regex(str1);
            string result = rgx.Replace(str, str2);
            return result;
        }
    /// <summary>
    /// 获得扩展名
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    static public string GetExName(string str)
    {
        string regexStr = @"(?<=\.)[^\.]+$";
        string strs = GetFirstMatch(str, regexStr);
        return strs;
    }

    /// <summary>
    /// 移除扩展名
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    static public string RemoveExName(string str)
    {
        string regexStr = @".+(?=\.)";
        string strs = GetFirstMatch(str, regexStr);
        if (string.IsNullOrEmpty(strs))
        {
            strs = str;
        }
        return strs;
    }

    /// <summary>
    /// 处理路径格式,把\\统一换成/
    /// </summary>
    /// <param name="path"></param>
    /// <returns></returns>
    static public string ChangePathFormat(string path)
    {
        string newPath = path.Replace('\\', '/');
        return newPath;
    }
    /// <summary>
    /// 字符串进行UrlEncode
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static string UrlEncode(string str)
    {
        return Uri.EscapeUriString(str);
    }

    #endregion

    #region 版本字符串对比
    /// <summary>
    /// 检查版本是否需要更新
    /// </summary>
    /// <param name="wwwVer"></param>
    /// <param name="localVer"></param>
    /// <returns></returns>
    static public bool isNeedUpdata(string wwwVer, string localVer)
    {
        if (string.IsNullOrEmpty(localVer))
        {
            return true;
        }
        string[] wwwVers = wwwVer.Split('.');
        string[] localVers = localVer.Split('.');
        int len = wwwVers.Length > localVers.Length ? wwwVers.Length : localVers.Length;
        bool needUpdata = false;
        int wwwValue;
        int localValue;
        for (int i = 0; i < len; i++)
        {
            wwwValue = GetValue(wwwVers, i);
            localValue = GetValue(localVers, i);
            if (wwwValue > localValue)
            {
                needUpdata = true;
                break;
            }
            if (localValue > wwwValue)
            {
                break;
            }
        }
        return needUpdata;
    }

    static private int GetValue(string[] strs, int ind)
    {
        if (strs.Length > ind)
        {
            int val = System.Int32.Parse(strs[ind]);
            return val;
        }
        else
        {
            return 0;
        }
    }
    /// <summary>
    /// 判断ver1是否比ver2版本号大
    /// </summary>
    /// <param name="ver1"></param>
    /// <param name="ver2"></param>
    /// <returns></returns>
    public static bool CompareVer(string ver1, string ver2)
    {
        string[] verStr1 = ver1.Split('.');
        string[] verStr2 = ver2.Split('.');
        int vn1 = 0;
        int vn2 = 0;
        for (int i = 0; i < verStr1.Length; i++)
        {
            if (i >= verStr2.Length)
            {
                return true;
            }
            vn1 = int.Parse(verStr1[i]);
            vn2 = int.Parse(verStr2[i]);
            if (vn1 > vn2)
            {
                return true;
            }
            if (vn1 < vn2)
            {
                return false;
            }
        }
        return false;
    }
    #endregion

    #region 字符串和Unicode码
    /// <summary>
    /// 从字符串获取unicode码
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    static public int String2Unicode(string str)
        {
            System.Text.UnicodeEncoding unicodeEncodeing = new System.Text.UnicodeEncoding();
            byte[] bs = unicodeEncodeing.GetBytes(str);
            int ts = 0;
            for (int i = 0; i < bs.Length; i++)
            {
                int sub = bs[i];
                int addSub = (int)Math.Pow(256, i) * sub;
                ts += addSub;
            }
            return ts;
        }

        /// <summary>
        /// 把字符串拆分再分别获取unicode码
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        static public int[] String2Unicodes(string str)
        {
            int[] res = new int[str.Length];
            for(int i = 0;i<str.Length;i++)
            {
                string subStr = str.Substring(i, 1);
                res[i] = String2Unicode(subStr);
            }
            return res;
        }


    #endregion


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值