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 ...
Get C# Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.