C# String LastIndexOf(String, Int32, Int32, StringComparison)

Description

String LastIndexOf(String, Int32, Int32, StringComparison) reports the zero-based index position of the last occurrence of a specified string within this instance. The search starts at a specified character position and proceeds backward toward the beginning of the string for the specified number of character positions. A parameter specifies the type of comparison to perform when searching for the specified string.

Syntax

String.LastIndexOf(String, Int32, Int32, StringComparison) has the following syntax.


public int LastIndexOf(
  string value,/*from w  ww  .j  a v  a2s.  c  o m*/
  int startIndex,
  int count,
  StringComparison comparisonType
)

Parameters

String.LastIndexOf(String, Int32, Int32, StringComparison) has the following parameters.

  • value - The string to seek.
  • startIndex - The search starting position. The search proceeds from startIndex toward the beginning of this instance.
  • count - The number of character positions to examine.
  • comparisonType - One of the enumeration values that specifies the rules for the search.

Returns

String.LastIndexOf(String, Int32, Int32, StringComparison) method returns The zero-based starting index position of the value parameter if that string is found, or -1 if it is not found or if the current instance equals String.Empty. If value is String.Empty, the return value is the smaller of startIndex and the last index position in this instance.

Example

In the following example, the LastIndexOf(String, Int32, Int32, StringComparison) method is used to find the position of a soft hyphen (U+00AD) followed by an "m" in all but the first character position before the final "m" in two strings.


/*from  ww  w .ja  v a2 s  .  c om*/
using System;

public class Example
{
   public static void Main()
   {
      string searchString = "\u00ADm";
      string s1 = "ani\u00ADmal" ;
      string s2 = "animal";
      int position;

      position = s1.LastIndexOf('m');
      if (position >= 1) {
         Console.WriteLine(s1.LastIndexOf(searchString, position, position, StringComparison.CurrentCulture));
         Console.WriteLine(s1.LastIndexOf(searchString, position, position, StringComparison.Ordinal));
      }      

      position = s2.LastIndexOf('m');
      if (position >= 1) { 
         Console.WriteLine(s2.LastIndexOf(searchString, position, position, StringComparison.CurrentCulture));
         Console.WriteLine(s2.LastIndexOf(searchString, position, position, StringComparison.Ordinal));
      }
   }
}

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