• <<字符串高级截取和统计>>一文的C#正则实现


    using System;
    using System.Text.RegularExpressions;
    
    namespace SubStringDemo
    {
        class Program
        {
            static void Main(string[] args)
            {
                string source = "123412355123559912323399";
                string destString = "123";
                Console.WriteLine("SubString count:" + SubString(source, destString));
                Console.WriteLine("SubString 2th:" + SubString(source, destString, 2));
                Console.WriteLine("" + SubString(source, destString, 4, 5));
                Console.ReadLine();
            }
            
            /// <summary>
            /// 统计源字符串中包含多少目标字符串
            /// </summary>
            /// <param name="source">源字符串</param>
            /// <param name="dest">目标字符串</param>
            /// <returns>出现次数</returns>
            private static int SubString(string source, string dest)
            {
                MatchCollection mc = Regex.Matches(source, dest);
                return mc.Count;
            }
    
            /// <summary>
            /// 获取目标字符串在源字符串中指定出现次数的索引
            /// </summary>
            /// <param name="source">源字符串</param>
            /// <param name="dest">目标字符串</param>
            /// <param name="ordinalNumber">出现序数</param>
            /// <returns>出现位置索引</returns>
            private static int SubString(string source, string dest, int ordinalNumber )
            {
                MatchCollection mc = Regex.Matches(source, dest);
                if (mc.Count < ordinalNumber)
                {
                    return -1;
                }
                else
                {
                    return mc[ordinalNumber - 1].Index;
                }
            }
    
            /// <summary>
            /// 获取源字符串中在指定序数的目标字符串之后的字符串
            /// </summary>
            /// <param name="source">源字符串</param>
            /// <param name="dest">目标字符串</param>
            /// <param name="ordinalNumber">出现序数</param>
            /// <param name="returnStringlength">返回字符串的长度</param>
            /// <returns>获取的字符串,不成功为null</returns>
            private static string SubString(string source, string dest, int ordinalNumber, int returnStringlength)
            {
                int pos = SubString(source, dest, ordinalNumber);
                if(pos != -1)
                {
                    return source.Substring(pos + dest.Length, returnStringlength);
                }
                else
                {
                    return null;
                }
            }
        }
    
    } 

    执行结果:

    SubString count:4
    SubString 2th:4
    23399

  • 相关阅读:
    [转]距离的计算方法
    [转]C#算法题
    varchar和nvarchar区别
    Request.QueryString 的用法
    CommandBehavior.CloseConnection有何作用
    fileupload简单使用
    (二十九)商品管理-添加商品
    (二十八)分类信息的curd-分类信息删除
    (二十七)分类信息的curd-分类信息修改
    (二十六)分类信息的curd-分类信息添加
  • 原文地址:https://www.cnblogs.com/wangchuang/p/2507405.html
Copyright © 2020-2023  润新知