O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

2.4. Finding All Occurrences of a Character Within a String

Problem

You need a way of searching a string for multiple occurrences of a specific character.

Solution

Use IndexOf in a loop to determine how many occurrences of a character exist, as well as identify their location within the string:

using System;
using System.Collections;

public static int[] FindAllOccurrences(char matchChar, string source)
{
    return (FindAllOccurrences(matchChar, source, -1, false));
}

public static int[] FindAllOccurrences(char matchChar, string source, 
                                           int maxMatches)
{
    return (FindAllOccurrences(matchChar, source, maxMatches, false));
}

public static int[] FindAllOccurrences(char matchChar, string source, 
                                           bool caseSensitivity)
{
    return (FindAllOccurrences(matchChar, source, -1, caseSensitivity));
}
        
public static int[] FindAllOccurrences(char matchChar, string source, 
                                           int maxMatches, bool caseSensitivity)
{
    ArrayList occurrences = new ArrayList( );
    int foundPos = -1;   // -1 represents not found
    int numberFound = 0;
    int startPos = 0;
    char tempMatchChar = matchChar;
    string tempSource = source;

    if (!caseSensitivity)
    {
        tempMatchChar = char.ToUpper(matchChar);
        tempSource = source.ToUpper( );
    }

    do
    {
        foundPos = tempSource.IndexOf(matchChar, startPos);        
        if (foundPos > -1)
        {
            startPos = foundPos + 1;
            numberFound++;

            if (maxMatches > -1 && numberFound > maxMatches)
            {
                break;
            }
            else
            {
                occurrences.Add(foundPos);
            }
        }
    }while (foundPos > -1);

    return ((int[])occurrences.ToArray(typeof(int)));
}

Discussion

The FindAllOccurrences ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required