Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't StringBuilder have IndexOf method?

Tags:

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.

like image 629
thorn0 Avatar asked Aug 31 '09 23:08

thorn0


People also ask

What indexOf () will do?

indexOf() The indexOf() method, given one argument: a substring to search for, searches the entire calling string, and returns the index of the first occurrence of the specified substring.

Does indexOf throw exception?

IndexOf() promises you to return the index of the first occurrence of a char/string. It would have thrown an exception if it was unable to do its job for some reason. It did its job but didn't find the string and hence returns -1 to convey the not-found result. File.

What does the method indexOf require as a parameter?

The indexOf method accepts two parameters. The first is the element to check if given array contains it or not. The other parameter, starting index, is optional.


1 Answers

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; } 
like image 177
Dennis Avatar answered Oct 24 '22 23:10

Dennis