C#
  Home arrow C# arrow Page 4 - Strings and Characters, Part 1
ASP Free Forums 
.NET  
ASP  
ASP Code  
ASP.NET  
ASP.NET Code  
BrainDump  
C#  
Code Examples  
Database  
Database Code  
IIS  
Microsoft Access  
MS SQL Server  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
ASP Web Hosting  
ASP.NET Web Hosting 
Mobile Linux 
App Generation ROI 
Windows Web Hosting
 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
C#

Strings and Characters, Part 1
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 3 stars3 stars3 stars3 stars3 stars / 17
    2004-07-21

    Table of Contents:
  • Strings and Characters, Part 1
  • 2.2 Determine if a character is in a Specified Range
  • 2.3 Controlling Case Sensitivity when Comparing Two Characters
  • 2.4 Finding All Occurrences of a Character Within a String
  • 2.5 Finding the Location of All Occurrences of a String Within Another String
  • 2.6 The Poor Man’s Tokenizer Problem
  • 2.7 Controlling Case Sensitivity when Comparing Two Strings
  • 2.8 Comparing a String to the Beginning or End of a Second String
  • 2.9 Inserting Text into a String
  • 2.10 Removing or Replacing Characters Within a String
  • 2.11 Encoding Binary Data as Base64
  • 2.12 Decoding a Base64-Encoded Binary

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Strings and Characters, Part 1 - 2.4 Finding All Occurrences of a Character Within a String


    (Page 4 of 12 )

    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 method is overloaded to allow the last two parameters (maxMatches and caseSensitivity) to be set to a default value if the developer chooses not to pass in one or both of these parameters. The maxMatches parameter defaults to -1, indicating that all matches are to be found. The caseSensitivity parameter defaults to false to allow for a case-insensitive search.

    The FindAllOccurrences method starts out by determining whether case sensitivity is turned on. If false was passed in to the caseSensitivity parameter, both matchChar and source are set to all uppercase. This prevents a case-sensitive search.

    The main loop in this method is a simple do loop that terminates when foundPos returns -1, meaning that no more matchChar characters can be found in the source string. We use a do loop so that the IndexOf operation would be executed at least one time before the check in the while clause is performed to determine whether there are any more character matches to be found in the source string.

    Once a match is found by the IndexOf method, the numberFound variable is incremented by one to indicate that another match was found, and startPos is moved past the previously found match to indicate where the next IndexOf operation should start. The startPos is increased to the starting position of the last match found plus one. The +1 is needed so that we do not keep matching the same character that was previously matched. An infinite loop would occur in the code if at least one match was found in the source string.

    Finally, a check is made to determine whether we are done searching for matchChar characters. If the maxMatches parameter is set to -1, the code keeps searching until it arrives at the end of the source string. Any other number indicates the maximum number of matchChar characters to search for. The maxMatches parameter limits the number of matches that can be made in the source string. If this check indicates that we are able to keep this match, it is stored in the occurrences ArrayList.

    Buy the book!If you've enjoyed what you've seen here, or to get more information, click on the "Buy the book!" graphic. Pick up a copy today!

    Visit the O'Reilly Network http://www.oreillynet.com for more online content.

    More C# Articles
    More By O'Reilly Media


     

    C# ARTICLES

    - Working with Dates and Times in C#
    - Generics, Dictionaries, and More
    - More About Generics
    - Working with C# Collections
    - Generics
    - C# and XML
    - Pointers and Arrays in C#
    - C# 3.0 Extension Methods
    - Overloading Operators in C#
    - Iterators and Nullable Types
    - Patterns and Iterators in C#
    - C# Exceptions
    - Methods in C#
    - Delegates and Events in C#
    - Advanced C#

     
    Best Practices for Windows Vista Migration Presentation
    Dell and Microsoft recently held a series of face-to-face seminars entitled, &qu....

     
    Creating a Culture for Code Reuse
    If you oversee development teams you know that like it or not proprietary and ex....

     
    Keys to Web Application Acceleration: Advances in Delivery Systems
    Accelerate Web apps by up to 5x. Ensure significantly faster access to the Web a....

     
    Optimizing Application Monitoring
    Tired of finding out from your customers that you're offline? This white paper e....

     
    Solaris to Solaris Migration -- Migrating applications from Sun SPARC to Dell PowerEdge R900
    This comprehensive Migration Guide reviews the approach that Principled Technolo....

     




    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 6 hosted by Hostway
    Stay green...Green IT