首页 > 技术文章 > 1、C# 字符串操作工具集

su1643 2017-03-30 19:29 原文

1、截取字符串

  (1)从左向右截取字符串

public static string Left(string sSource, int iLength)
    {
        return sSource.Substring(0, iLength > sSource.Length ? sSource.Length : iLength);
    }

 

  (2)从右向左截取字符串

public static string Right(string sSource, int iLength)
    {
        return sSource.Substring(iLength > sSource.Length ? 0 : sSource.Length - iLength);
    }

   (3)从中间截取字符串

public static string Mid(string sSource, int iStart, int iLength)
    {
        int iStartPoint = iStart > sSource.Length ? sSource.Length : iStart;
        return sSource.Substring(iStartPoint, iStartPoint + iLength > sSource.Length ? sSource.Length - iStartPoint : iLength);
    }

 

2、拆分字符串

public static string[] splt(string str, string s)
    {
        return Regex.Split(str, s, RegexOptions.IgnoreCase);
    }

 

3、判断是否为整数字符串

//判断是否为整数字符串
    public static bool isNumberic(string str)
    {
        long i;
        try
        {
            i = long.Parse(str);
            return true;
        }
        catch
        {
            return false;
        }
    }

 4、格式化文件名

//格式化文件名,将无效字符去掉
    static public string fmtFileName(string str)
    {
        string tmp;
        tmp = str.Replace("\\", "");
        tmp = tmp.Replace("/", "");
        tmp = tmp.Replace(":", "");
        tmp = tmp.Replace("*", "");
        tmp = tmp.Replace("?", "");
        tmp = tmp.Replace("\"", "");
        tmp = tmp.Replace("<", "");
        tmp = tmp.Replace(">", "");
        tmp = tmp.Replace("|", "");
        tmp = tmp.Replace(",", "");
        tmp = tmp.Replace("\'", "");
        tmp = tmp.Replace("\"", "");
        return tmp;
    }

5、取汉字首字母

//取汉字首字母
    static public string GetChineseSpell(string strText)
    {
        int len = strText.Length;
        string myStr = "";
        for (int i = 0; i < len; i++)
        {
            myStr += getSpell(strText.Substring(i, 1));
        }
        return myStr;
    }

    static public string getSpell(string myChar)
    {
        byte[] arrCN = System.Text.Encoding.Default.GetBytes(myChar);
        if (arrCN.Length > 1)
        {
            int area = (short)arrCN[0];
            int pos = (short)arrCN[1];
            int code = (area << 8) + pos;
            int[] areacode = { 45217, 45253, 45761, 46318, 46826, 47010, 47297, 47614, 48119, 48119, 49062, 49324, 49896, 50371, 50614, 50622, 50906, 51387, 51446, 52218, 52698, 52698, 52698, 52980, 53689, 54481 };
            for (int i = 0; i < 26; i++)
            {
                int max = 55290;
                if (i != 25) max = areacode[i + 1];
                if (areacode[i] <= code && code < max)
                {
                    return System.Text.Encoding.Default.GetString(new byte[] { (byte)(65 + i) });
                }
            }
            return " ";
        }
        else return myChar;
    }

 

 

  

 

推荐阅读