.net - Finding ALL positions of a substring in a large string in C# -


i have large string need parse, , need find instances of extract"(me,i-have lots. of]punctuation, , store them list.

so piece of string in beginning , middle of larger string, both of them found, , indexes added list. , list contain 0 , other index whatever be.

i've been playing around, , string.indexof almost i'm looking for, , i've written code. can't seem work:

list<int> inst = new list<int>(); int index = 0; while (index < source.lastindexof("extract\"(me,i-have lots. of]punctuation", 0) + 39) {     int src = source.indexof("extract\"(me,i-have lots. of]punctuation", index);     inst.add(src);     index = src + 40; } 
  • inst = list
  • source = large string

any better ideas?

here's example extension method it:

public static list<int> allindexesof(this string str, string value) {     if (string.isnullorempty(value))         throw new argumentexception("the string find may not empty", "value");     list<int> indexes = new list<int>();     (int index = 0;; index += value.length) {         index = str.indexof(value, index);         if (index == -1)             return indexes;         indexes.add(index);     } } 

if put static class , import namespace using, appears method on string, , can do:

list<int> indexes = "foostringfoobar".allindexesof("foo"); 

for more information on extension methods, http://msdn.microsoft.com/en-us/library/bb383977.aspx

also same using iterator:

public static ienumerable<int> allindexesof(this string str, string value) {     if (string.isnullorempty(value))         throw new argumentexception("the string find may not empty", "value");     (int index = 0;; index += value.length) {         index = str.indexof(value, index);         if (index == -1)             break;         yield return index;     } } 

Comments

Popular posts from this blog

twig - Using Twigbridge in a Laravel 5.1 Package -

jdbc - Not able to establish database connection in eclipse -

Kivy: Swiping (Carousel & ScreenManager) -