C# 字符串 - IndexOf() 方法

C# 字符串 IndexOf() 方法用于查找当前字符串对象中指定字符或字符串首次出现的索引(从零开始)。如果未找到字符或字符串,则返回 -1。

需要注意的是,此方法可以通过传递不同的参数进行重载。

语法

以下是 C# 字符串 IndexOf() 方法的语法: IndexOf() -

public int IndexOf(char x)

参数

此方法接受一个 Char 类型的参数 char x,该参数指定要搜索的字符。

返回值

如果找到该字符,此方法返回一个 32 位有符号整数,表示该值的索引位置。否则返回 -1。

示例 1:使用 IndexOf(char x) 语法

以下是使用 IndexOf(char x) 方法查找字符串中字符索引的基本示例 -

using System;
class Program {
   static void Main() {
      string str = "tutorialspoint";
      
      int indx = str.IndexOf('l');
      Console.Write("The Index Value of character 'l' is " + indx);
   }
}

输出

以下是输出 -

The Index Value of character 'l' is 7

示例 2:使用 IndexOf(char x, int start1) 语法

让我们来看另一个 IndexOf(char x, int start1) 方法的示例。在这里,我们使用另一种语法来查找从指定索引开始的指定字符的索引 -

using System;
class Program {
   static void Main() {
      string str = "tutorialspoint";
      
      int indx = str.IndexOf('a', 7);
      Console.WriteLine("The Index Value of character 'a' "+ "with start index 7 is " + indx);
   }
}

输出

以下是输出 -

The Index Value of character 'a' with start index 7 is -1

示例 3:使用 IndexOf(char x, int start1, int start2) 语法

在此示例中,我们使用 IndexOf(char x, int startIndex, int endIndex) 方法在指定范围内查找指定字符的索引,并明确定义搜索的起始和结束索引 -

using System;
class Program {
   static void Main(string[] args) {   
   	   string str = "Your Life My Rules";
   	   int index1 = str.IndexOf('R', 2, 14);
   	   // Here starting index is < Index value of 'R'
   	   // Also ending index is > Index of 'R'
   	   Console.WriteLine("Index Value of 'R' with start" + " Index = 2 and end Index = 15 is " + index1);
   }
}

输出

以下是输出 -

Index Value of 'R' with start Index = 2 and end Index = 15 is 13

示例 4:使用 IndexOf(string s1) 语法

在本例中,我们使用 IndexOf(string s1) 方法查找字符串中某个子字符串首次出现的索引。如果未找到该子字符串,则该方法返回 -1 −

using System;
class Program {
   static void Main(string[] args) {
      string str = "Hello tutorialspoint....How are you...";     
      // 使用 indexOf(string s1) 语法
      int indx = str.IndexOf("tutorialspoint"); 
      Console.WriteLine("First value Index of 'How' is " + indx);
   }
}

输出

以下是输出 -

First value Index of 'How' is 6

csharp_strings.html