Common C string manipulation tools class code sharing

  • 2020-06-19 11:34:07
  • OfStack

Achieve the following functions:

Verify that the string consists of a plus or minus sign (+-), a number, a decimal point, and only one decimal point at most
Verify that the string consists only of [0-9]
Verify that the string consists of letters and Numbers
Verify that it is an empty string. It is recommended to use String.IsNullOrEmpty(string) if you do not need to cut both ends of the space.
Cropped string (Chinese is calculated as two characters)
Cut string (Chinese is calculated as two characters, Html label will be filtered before cutting)
Filter HTML tags
Gets the length of the string. Unlike ES15en.Length, this method counts Chinese as two characters.
Restore a user-friendly file size string like 10.1MB to its true file size in bytes.
Verify that the string conforms to the folder format based on the folder naming rules
Verify that the string conforms to the file name format based on the file name naming rules
Verify that it is a valid RGB color string

C # code:


public static class ExtendedString
{
    /// <summary>
    ///  Verify that the string is marked with a plus or minus sign ( +- ), Numbers, decimal points, and, at most, only 1 A decimal point 
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static bool IsNumeric(this string str)
    {
        Regex regex = new Regex(@"^[+-]?\d+[.]?\d*$");
        return regex.IsMatch(str);           
    }

    /// <summary>
    ///  Verify that the string is made up only of [0-9] Constitute a 
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static bool IsNumericOnly(this string str)
    {
        Regex regex = new Regex("[0-9]");
        return regex.IsMatch(str);
    }

    /// <summary>
    ///  Verify that the string consists of letters and Numbers 
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static bool IsNumericOrLetters(this string str)
    {
        Regex regex = new Regex("[a-zA-Z0-9]");
        return regex.IsMatch(str);
    }

    /// <summary>
    ///  Verify that it is an empty string. If there is no need to cut both ends of the space, it is recommended to use directly  String.IsNullOrEmpty(string)
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    /// <remarks>
    ///  Different from the String.IsNullOrEmpty(string) , this method will increase 1 step Trim Operation. Such as  IsNullOrEmptyStr(" ")  Will return  true . 
    /// </remarks>
    public static bool IsNullOrEmptyStr(this string str)
    {
        if (string.IsNullOrEmpty(str)) { return true; }
        if (str.Trim().Length == 0) { return true; }
        return false;
    }

    /// <summary>
    ///  Cropped string (Chinese is calculated as two characters) 
    /// </summary>
    /// <param name="str"> The old string </param>
    /// <param name="len"> New string length </param>
    /// <param name="HtmlEnable"> for  false  When the filter  Html  After the label is cut, otherwise retained  Html  The label. </param>
    /// <remarks>
    /// <para> Note: <ol>
    /// <li> If the string is truncated, appends" ... ", or simply returns the original string. </li>
    /// <li> parameter  <paramref name="HtmlEnable"/>  for  false  Will be called first <see cref="uoLib.Common.Functions.HtmlFilter"/> To filter out  Html  The label is then cut. </li>
    /// <li> Chinese is calculated as two characters. If the specified length position gets exactly half a Chinese character, it will be completed, as shown in the following example: <br/>
    /// <code><![CDATA[
    /// string str = " Thank you for using uoLib . ";
    /// string A = CutStr(str,4);   // A = " Thank you for ..."
    /// string B = CutStr(str,5);   // B = " Thank you for that ..."
    /// ]]></code></li>
    /// </ol>
    /// </para>
    /// </remarks>
    public static string CutStr(this string str, int len, bool HtmlEnable)
    {
        if (str == null || str.Length == 0 || len <= 0) { return string.Empty; }

        if (HtmlEnable == false) str = HtmlFilter(str);
        int l = str.Length;

        #region  Calculate the length of the 
        int clen = 0;// The current length 
        while (clen < len && clen < l)
        {
            // Each encounter 1 For Chinese, the target length will be reduced 1 . 
            if ((int)str[clen] > 128) { len--; }
            clen++;
        }
        #endregion

        if (clen < l)
        {
            return str.Substring(0, clen) + "...";
        }
        else
        {
            return str;
        }
    }
    /// <summary>
    ///  Clipping string (Chinese is calculated as two characters, filtered before clipping  Html  The label) 
    /// </summary>
    /// <param name="str"> The old string </param>
    /// <param name="len"> New string length </param>
    /// <remarks>
    /// <para> Note: <ol>
    /// <li> If the string is truncated, appends" ... ", or simply returns the original string. </li>
    /// <li> Chinese is calculated as two characters. If the specified length position gets exactly half a Chinese character, it will be completed, as shown in the following example: <br/>
    /// <code><![CDATA[
    /// string str = " Thank you for using uoLib The module. ";
    /// string A = CutStr(str,4);   // A = " Thank you for ..."
    /// string B = CutStr(str,5);   // B = " Thank you for that ..."
    /// ]]></code></li>
    /// </ol>
    /// </para>
    /// </remarks>
    public static string CutStr(this string str, int len)
    {
        if (IsNullOrEmptyStr(str)) { return string.Empty; }
        else
        {
            return CutStr(str, len, false);
        }
    }
    /// <summary>
    ///  filter HTML The label 
    /// </summary>
    public static string HtmlFilter(this string str)
    {
        if (IsNullOrEmptyStr(str)) { return string.Empty; }
        else
        {
            Regex re = new Regex(RegexPatterns.HtmlTag, RegexOptions.IgnoreCase);
            return re.Replace(str, "");
        }
    }

    /// <summary>
    ///  Gets the length of the string. with string.Length The difference is that the method USES Chinese characters  2  Two character calculation. 
    /// </summary>
    /// <param name="str"> Target string </param>
    /// <returns></returns>
    public static int GetLength(this string str)
    {
        if (str == null || str.Length == 0) { return 0; }

        int l = str.Length;
        int realLen = l;

        #region  Calculate the length of the 
        int clen = 0;// The current length 
        while (clen < l)
        {
            // Each encounter 1 In Chinese, the actual length is added 1 . 
            if ((int)str[clen] > 128) { realLen++; }
            clen++;
        }
        #endregion

        return realLen;
    }

    /// <summary>
    ///  Will be like  10.1MB  The format restores the user-friendly file size string to the true file size in bytes. 
    /// </summary>
    /// <param name="formatedSize"> like  10.1MB  Format file size string </param>
    /// <remarks>
    ///  See also: <see cref="uoLib.Common.Functions.FormatFileSize(long)"/>
    /// </remarks>
    /// <returns></returns>
    public static long GetFileSizeFromString(this string formatedSize)
    {
        if (IsNullOrEmptyStr(formatedSize)) throw new ArgumentNullException("formatedSize");

        long size;
        if (long.TryParse(formatedSize, out size)) return size;

        // Remove the numeric separator 
        formatedSize = formatedSize.Replace(",", "");

        Regex re = new Regex(@"^([\d\.]+)((?:TB|GB|MB|KB|Bytes))$");
        if (re.IsMatch(formatedSize))
        {
            MatchCollection mc = re.Matches(formatedSize);
            Match m = mc[0];
            double s = double.Parse(m.Groups[1].Value);

            switch (m.Groups[2].Value)
            {
                case "TB":
                    s *= 1099511627776;
                    break;
                case "GB":
                    s *= 1073741824;
                    break;
                case "MB":
                    s *= 1048576;
                    break;
                case "KB":
                    s *= 1024;
                    break;
            }

            size = (long)s;
            return size;
        }

        throw new ArgumentException("formatedSize");
    }

    /// <summary>
    ///  Verify that the string conforms to the folder format based on the folder naming rules 
    /// </summary>
    public static bool IsFolderName(this string folderName)
    {
        if (IsNullOrEmptyStr(folderName)) { return false; }
        else
        {
            //  Not to   " . "   At the beginning 
            folderName = folderName.Trim().ToLower();

            //  " nul "," aux "," con "," com1 "," lpt1 "Cannot be a folder / File name 
            //  As a folder, you just need to satisfy the name is not these. 
            switch (folderName)
            {
                case "nul":
                case "aux":
                case "con":
                case "com1":
                case "lpt1":
                    return false;
                default:
                    break;
            }

            Regex re = new Regex(RegexPatterns.FolderName, RegexOptions.IgnoreCase);
            return re.IsMatch(folderName);
        }
    }

    /// <summary>
    ///  Verify that the string conforms to the file name format based on the file name naming rules 
    /// </summary>
    public static bool IsFileName(this string fileName)
    {
        if (IsNullOrEmptyStr(fileName)) { return false; }
        else
        {
            fileName = fileName.Trim().ToLower();
            //  Not to   " . "   At the beginning 
            //  As a file name, the 1 A" . "   It couldn't have been" nul "," aux "," con "," com1 "," lpt1 " 
            if (fileName.StartsWith(".")
                || fileName.StartsWith("nul.")
                || fileName.StartsWith("aux.")
                || fileName.StartsWith("con.")
                || fileName.StartsWith("com1.")
                || fileName.StartsWith("lpt1.")
                ) return false;

            Regex re = new Regex(RegexPatterns.FileName, RegexOptions.IgnoreCase);
            return re.IsMatch(fileName);
        }
    }

    /// <summary>
    ///  Verify that it is valid RGB Color string 
    /// </summary>
    /// <param name="color">RGB Color, such as: #00ccff | #039 | ffffcc</param>
    /// <returns></returns>
    public static bool IsRGBColor(this string color)
    {
        if (IsNullOrEmptyStr(color)) { return false; }
        else
        {
            Regex re = new Regex(RegexPatterns.HtmlColor, RegexOptions.IgnoreCase);
            return re.IsMatch(color);
        }
    }

    public static string GetJsSafeStr(this string str)
    {
        if (string.IsNullOrEmpty(str))
            return string.Empty;

        return str.Replace("\\", "\\\\").Replace("\"", "\\\"");
    }
}


Related articles: