次の拡張メソッドを使用して、パス区切り文字の最後の n 番目のインデックスまでの文字インデックスを取得し、正しい部分文字列を返すことができます。
using System;
using System.Linq;
public static class StringExtensions
{
public static int NthLastIndexOf(this string value, char c, int n = 1)
{
if (count < 1)
{
throw new ArgumentOutOfRangeException("count must be greater than 0.");
}
var index = 1;
for (int i = value.Length - 1; i >= 0; i--)
{
if (value[i] == c)
{
if (index == n)
{
return i;
}
index++;
}
}
return -1;
}
}
class Program
{
public static string GetEndOfPath(string path)
{
var idx = path.NthLastIndexOf('/', 2);
if (idx == -1)
{
throw new ArgumentException("path does not contain two separators.");
}
return path.Substring(idx + 1);
}
static void Main()
{
var result = GetEndOfPath("http://users/test/test/program/test/test.avi");
Console.WriteLine(result);
}
}
拡張メソッドNthLastIndexOf
は、指定された Unicode 文字が最後に n 番目に出現するゼロベースのインデックス位置を返します。文字列内で少なくとも n 回文字が見つからない場合、メソッドは -1 を返します。