C# String IndexOf(Char, Int32, Int32)

Description

String IndexOf(Char, Int32, Int32) reports the zero-based index of the first occurrence of the specified character in this instance. The search starts at a specified character position and examines a specified number of character positions.

Syntax

String.IndexOf(Char, Int32, Int32) has the following syntax.


public int IndexOf(
  char value,//from  w w w .  ja v a2  s  .  c o  m
  int startIndex,
  int count
)

Parameters

String.IndexOf(Char, Int32, Int32) has the following parameters.

  • value - A Unicode character to seek.
  • startIndex - The search starting position.
  • count - The number of character positions to examine.

Returns

String.IndexOf(Char, Int32, Int32) method returns The zero-based index position of value if that character is found, or -1 if it is not.

Example

The following example demonstrates the IndexOf method.


//from ww  w .  ja va2s  .  c  om
using System;

class IndexOfCII 
{
    public static void Main() 
    {
        string searched = "ABCDEFGHI  ABCDEFGHI  " +
            "ABCDEFGHI abcdefghi ABCDEFGHI";

        Char target= 'A';

        int     startIndex = -1;
        int     hitCount = 0;

        // Search for all occurrences of the target. 
        while( true ){
            startIndex = searched.IndexOf( 
                target, startIndex + 1, 
                searched.Length - startIndex - 1 );

            // Exit the loop if the target is not found. 
            if( startIndex < 0 )
                break;

            Console.Write( "{0}, ", startIndex );
            hitCount++;
        }

        Console.WriteLine( "occurrences: {0}", hitCount );
    }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    System »




Array
BitConverter
Boolean
Byte
Char
Console
ConsoleKeyInfo
Convert
DateTime
DateTimeOffset
Decimal
Double
Enum
Environment
Exception
Guid
Int16
Int32
Int64
Math
OperatingSystem
Random
SByte
Single
String
StringComparer
TimeSpan
TimeZone
TimeZoneInfo
Tuple
Tuple
Tuple
Type
UInt16
UInt32
UInt64
Uri
Version