Smilla J.
Smilla J.

Reputation: 1164

StringBuilder - find last index of a character

I'd like to find a specific last character in a StringBuilder.
I know, I can solve it with while() but is there an build it option to do that easily?

eg:

private static StringBuilder mySb = new StringBuilder("");
mySb.Add("This is a test[n] I like Orange juice[n] Can you give me some?");

Now: It shoud find the ] and give me the possition. Like: 40

Thanks in advance

Upvotes: 3

Views: 7172

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460098

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

Upvotes: 5

bobthedeveloper
bobthedeveloper

Reputation: 3783

Convert the StringBuilder to a string with the toString method, thereafter you can make use of the LastIndexOf method.

mySb.ToString().LastIndexOf(']');

LastIndexOf:

Reports the zero-based index position of the last occurrence of a specified Unicode character or string within this instance. The method returns -1 if the character or string is not found in this instance.

This member is overloaded. For complete information about this member, including syntax, usage, and examples, click a name in the overload list.

Upvotes: -3

Related Questions