Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

10
  • 74
    SUPER SLOW! Tried it on a page of html and it took about 2 minutes as versus other methods on this page that took 2 seconds. The answer was correct; it was just too slow to be usable. Commented Jun 20, 2012 at 21:51
  • 7
    Note that the reason this is so slow is that it creates n strings, thus allocating roughly n^2/2 bytes. Commented Feb 7, 2013 at 19:32
  • 8
    OutOfMemoryException is thrown for my 210000 chars of string. Commented Sep 13, 2013 at 8:47
  • 2
    src.Where((c, i) => src.Skip(i).Take(target.Length).SequenceEqual(target)).Count() consumes less memory and runs faster :) Commented Feb 22, 2019 at 15:00
  • 3
    Now, with the new Span APIs, you can do this m̶o̶r̶e̶ ̶e̶f̶f̶i̶c̶i̶e̶n̶t̶l̶y̵ less inefficiently. :) First prep two variables, srcSpan = src.AsSpan() and targetSpan = target.AsSpan(). Then replace src.Substring(i) by srcSpan.Slice(i), and replace sub.StartsWith(target) by sub.StartsWith(targetSpan). This avoids the ridiculous number of heap allocations, but not the O(N^2) time complexity. Commented Jul 2, 2019 at 12:17