System.String.IndexOf 方法 (String, Int32, Int32)

方法描述

报告指定字符串在此实例中的第一个匹配项的索引。 搜索从指定字符位置开始,并检查指定数量的字符位置。

语法定义(C# System.String.IndexOf 方法 (String, Int32, Int32) 的用法)

public int IndexOf(
	string value,
	int startIndex,
	int count
)

参数/返回值

参数值/返回值 参数类型/返回类型 参数描述/返回描述
value System-String 要搜寻的字符串。
startIndex System-Int32 搜索起始位置。
count System-Int32 要检查的字符位置数。
返回值 System.Int32 如果找到该字符串,则为 value 的从零开始的索引位置;如果未找到该字符串,则为 -1。 如果 value 为 String.Empty,则为 startIndex。

提示和注释

索引编号从零开始。 startIndex 参数的范围可以从 0 到字符串实例的长度减一。

此方法使用当前区域性执行单词(区分大小写和区域性)搜索。 搜索从 startIndex 开始,并且一直搜索至 startIndex + count -1。 startIndex + count 位置上的字符不在搜索范围内。

对调用者的说明

如 在 .NET Framework 中使用字符串的最佳做法 中所述,我们建议您避免调用替换默认值的字符串比较方法,而是调用需要显式指定参数的方法。 若要使用当前区域性的比较规则执行此操作,请为它的 comparisonType 参数使用 StringComparison.CurrentCulture 的值来调用 IndexOf(String, Int32, Int32, StringComparison) 方法重载。

System.String.IndexOf 方法 (String, Int32, Int32)例子

注意,对于每次搜索迭代,必须重新计算待搜索字符的个数。

// Sample for String.IndexOf(String, Int32, Int32)
using System;

class Sample {
    public static void Main() {

    string br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-";
    string br2 = "0123456789012345678901234567890123456789012345678901234567890123456";
    string str = "Now is the time for all good men to come to the aid of their party.";
    int start;
    int at;
    int end;
    int count;

    end = str.Length;
    start = end/2;
    Console.WriteLine();
    Console.WriteLine("All occurrences of 'he' from position {0} to {1}.", start, end-1);
    Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str);
    Console.Write("The string 'he' occurs at position(s): ");

    count = 0;
    at = 0;
    while((start <= end) && (at > -1))
        {
// start+count must be a position within -str-.
        count = end - start;
        at = str.IndexOf("he", start, count);
        if (at == -1) break;
        Console.Write("{0} ", at);
        start = at+1;
        }
    Console.WriteLine();
    }
}
/*
This example produces the following results:

All occurrences of 'he' from position 33 to 66.
0----+----1----+----2----+----3----+----4----+----5----+----6----+-
0123456789012345678901234567890123456789012345678901234567890123456
Now is the time for all good men to come to the aid of their party.

The string 'he' occurs at position(s): 45 56

*/

异常

异常 异常描述
ArgumentNullException value 为 null。
ArgumentOutOfRangeException
  • count 或 startIndex 为负。
  • count 加 startIndex 之和指定的位置不在此实例中。

命名空间

namespace: System

程序集: mscorlib(在 mscorlib.dll 中)

版本信息

.NET Framework 受以下版本支持:4、3.5、3.0、2.0、1.1、1.0 .NET Framework Client Profile 受以下版本支持:4、3.5 SP1

适用平台

Windows 7, Windows Vista SP1 或更高版本, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008(不支持服务器核心), Windows Server 2008 R2(支持 SP1 或更高版本的服务器核心), Windows Server 2003 SP2 .NET Framework 并不是对每个平台的所有版本都提供支持。有关支持的版本的列表,请参见.NET Framework 系统要求。