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(); } ////// 统计源字符串中包含多少目标字符串 /// /// 源字符串 /// 目标字符串 ///出现次数 private static int SubString(string source, string dest) { MatchCollection mc = Regex.Matches(source, dest); return mc.Count; } ////// 获取目标字符串在源字符串中指定出现次数的索引 /// /// 源字符串 /// 目标字符串 /// 出现序数 ///出现位置索引 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; } } ////// 获取源字符串中在指定序数的目标字符串之后的字符串 /// /// 源字符串 /// 目标字符串 /// 出现序数 /// 返回字符串的长度 ///获取的字符串,不成功为null 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:423399