
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Finding All Occurrences of a Character Within a String
|
41
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 to identify their location within the string:
using System;
using System.Collections;
using System.Collections.Generic;
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)
{
List<int> occurrences = new List<int>( );
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
{