Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
334 views
in Technique[技术] by (71.8m points)

.net - Why doesn't StringBuilder have IndexOf method?

I understand that I can call ToString().IndexOf(...), but I don't want to create an extra string. I understand that I can write a search routine manually. I just wonder why such a routine doesn't already exist in the framework.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I know this is an old question, however I have written a extension method that performs an IndexOf on a StringBuilder. It is below. I hope it helps anyone that finds this question, either from a Google search or searching StackOverflow.

/// <summary>
/// Returns the index of the start of the contents in a StringBuilder
/// </summary>        
/// <param name="value">The string to find</param>
/// <param name="startIndex">The starting index.</param>
/// <param name="ignoreCase">if set to <c>true</c> it will ignore case</param>
/// <returns></returns>
public static int IndexOf(this StringBuilder sb, string value, int startIndex, bool ignoreCase)
{            
    int index;
    int length = value.Length;
    int maxSearchLength = (sb.Length - length) + 1;

    if (ignoreCase)
    {
        for (int i = startIndex; i < maxSearchLength; ++i)
        {
            if (Char.ToLower(sb[i]) == Char.ToLower(value[0]))
            {
                index = 1;
                while ((index < length) && (Char.ToLower(sb[i + index]) == Char.ToLower(value[index])))
                    ++index;

                if (index == length)
                    return i;
            }
        }

        return -1;
    }

    for (int i = startIndex; i < maxSearchLength; ++i)
    {
        if (sb[i] == value[0])
        {
            index = 1;
            while ((index < length) && (sb[i + index] == value[index]))
                ++index;

            if (index == length)
                return i;
        }
    }

    return -1;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...