Since there is no builtin method and always creating a string
from the StringBuilder
via ToString
can be quite inefficient you could create an extension method for this purpose:
public static int LastIndexOf(this StringBuilder sb, char find, bool ignoreCase = false, int startIndex = -1, CultureInfo culture = null)
{
if (sb == null) throw new ArgumentNullException(nameof(sb));
if (startIndex == -1) startIndex = sb.Length - 1;
if (startIndex < 0 || startIndex >= sb.Length) throw new ArgumentException("startIndex must be between 0 and sb.Lengh-1", nameof(sb));
if (culture == null) culture = CultureInfo.InvariantCulture;
int lastIndex = -1;
if (ignoreCase) find = Char.ToUpper(find, culture);
for (int i = startIndex; i >= 0; i--)
{
char c = ignoreCase ? Char.ToUpper(sb[i], culture) : (sb[i]);
if (find == c)
{
lastIndex = i;
break;
}
}
return lastIndex;
}
Add it to a static, accessible (extension) class, then you can use it in this way:
StringBuilder mySb = new StringBuilder("");
mySb.Append("This is a test[n] I like Orange juice[n] Can you give me some?");
int lastIndex = mySb.LastIndexOf(']'); // 39