看了<<字串進階截取和統計>>一文,確實正則可以實現,而且更為簡單,後來看到<<字串進階截取和統計>>一文的看法與Regex的實現中用java實現,所以我簡單寫了一下,把c#的實現貼出來。寫到不好之處,大家多多指教。
實現原理:
使用Regex中的MatchCollection類,它會把搜尋到的字串儲存到一個數組中,並包含相關資訊。
代碼:
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