Quantcast
Channel: Martijn's C# Programming Blog » Beginner
Viewing all articles
Browse latest Browse all 10

Manipulating Strings in C# – Finding all occurrences of a string within another string

$
0
0

A common programming problem is to find the position of all copies of a string in another string. For finding the first copy the C# string method IndexOf is similar to the C strpos() function. It returns the first occurrence of a string in another string. But what if you would like to find the position of all occurances of the substring? The following “IndexOfAll” method does just that. It returns an IEnumerable containing the offsets of each sub-string in the main string.

Because you might want to use this code throughout your project it is implemented as an Extension class. Simply put: the IndexOfAll method is attached to the String class. So if we want to call it we can just use .IndexOfAll(needle)

To be able to define an extension we need to create a static method and put it into a static class. The first parameter of the method identifies the class the method should associate with. In our case: string. We do this by defining it as “this string”.

using System;
using System.Collections;

namespace StringItems
{
    static class StringExt
    {
        public static IEnumerable IndexOfAll(this string haystack, string needle)
        {
            int pos,offset = 0;
            while ((pos = haystack.IndexOf(needle))>0)
            {
                haystack = haystack.Substring(pos+needle.Length);
                offset += pos;
                yield return offset;
            }
        }
    }

    class MainClass
    {
        public static void Main(string[] args)
        {
            string needle = "x";
            string haystack = "3 x 4 = 2 x 6 = 1 x 12";
            foreach(int Pos in haystack.IndexOfAll(needle))
                Console.WriteLine("Offset: {0}",Pos);
        }
    }
}

This is a post from Martijn's C# Coding Blog.


Viewing all articles
Browse latest Browse all 10

Trending Articles