System.String.IndexOf 方法 (String)

方法描述

报告指定字符串在此实例中的第一个匹配项的索引。

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

public int IndexOf(
	string value
)

参数/返回值

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

提示和注释

索引编号从零开始。

此方法使用当前区域性执行单词(区分大小写和区域性)搜索。 该搜索从此实例的第一个字符位置开始,一直搜索到最后一个字符位置。

对调用者的说明

如 在 .NET Framework 中使用字符串的最佳做法 中所述,我们建议您避免调用替换默认值的字符串比较方法,而是调用需要显式指定参数的方法。 若要使用当前区域性的比较规则查找在字符串实例内某个子字符串的第一个索引,请为它的 comparisonType 参数使用 StringComparison.CurrentCulture 的值调用 IndexOf(String, StringComparison) 方法重载。

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

然后,该方法在此位置插入一个形容词来描述句子中的动物。

using System;

public class InsertTest {
    public static void Main() 
    {
        string animal1 = "fox";
        string animal2 = "dog";

        string strTarget = String.Format("The {0} jumped over the {1}.", animal1, animal2);

        Console.WriteLine("The original string is:{0}{1}{0}", Environment.NewLine, strTarget);

        Console.Write("Enter an adjective (or group of adjectives) to describe the {0}: ==> ", animal1);
        string adj1 = Console.ReadLine();

        Console.Write("Enter an adjective (or group of adjectives) to describe the {0}: ==> ", animal2);    
        string adj2 = Console.ReadLine();

        adj1 = adj1.Trim() + " ";
        adj2 = adj2.Trim() + " ";

        strTarget = strTarget.Insert(strTarget.IndexOf(animal1), adj1);
        strTarget = strTarget.Insert(strTarget.IndexOf(animal2), adj2);

        Console.WriteLine("{0}The final string is:{0}{1}", Environment.NewLine, strTarget);
    }
}
// Output from the example might appear as follows:
//       The original string is:
//       The fox jumped over the dog.
//       
//       Enter an adjective (or group of adjectives) to describe the fox: ==> bold
//       Enter an adjective (or group of adjectives) to describe the dog: ==> lazy
//       
//       The final string is:
//       The bold fox jumped over the lazy dog.

异常

异常 异常描述
ArgumentNullException value 为 null。

命名空间

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 系统要求。