Returns the index of the Nth occurrence of a string - CSharp System

CSharp examples for System:String Search

Description

Returns the index of the Nth occurrence of a string

Demo Code

// Copyright (c) 2012 Computer Technology Solutions, Inc.  ALL RIGHTS RESERVED
using System.Text.RegularExpressions;
using System.Text;
using System.Linq;
using System.Globalization;
using System.Collections.Generic;
using System;/* www .  java2 s  . co  m*/

public class Main{
        /// <summary>
        /// Returns the index of the Nth occurrence of a string
        /// Code from: http://stackoverflow.com/questions/186653/c-sharp-indexof-the-nth-occurrence-of-a-string
        /// </summary>
        public static int IndexOfOccurence(this string s, string match, int occurrence)
        {
            int i = 1;
            int index = 0;
            while (i <= occurrence && (index = s.IndexOf(match, index + 1)) != -1)
            {
                if (i == occurrence) return index;
                i++;
            }

            return -1;
        }
}

Related Tutorials