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

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 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
{
}
}
}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.

No credit card required