String 的 IndexOf()
方法返回指定字符/子字符串在字符串中第一次出现的索引。
示例
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
string str = "Ice cream";
// returns index of substring cream
int result = str.IndexOf("cream");
Console.WriteLine(result);
Console.ReadLine();
}
}
}
// Output: 4
IndexOf() 语法
字符串 IndexOf()
方法的语法是:
String.IndexOf(string value, int startindex, int count)
这里,IndexOf()
是 String
类的一个方法。
IndexOf() 参数
IndexOf()
方法接受以下参数:
- value - 要搜索的字符串
- startIndex - 搜索的起始位置
- count - 要检查的字符数
IndexOf() 返回值
IndexOf()
方法返回:
- index - 指定字符/字符串第一次出现的索引
- -1 - 如果找不到指定的字符/字符串
示例 1:C# String IndexOf()
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
string str = "Ice cream";
int result;
// returns index of character 'I'
result = str.IndexOf('I');
Console.WriteLine("Index of I: " + result);
// returns -1
result = str.IndexOf('P');
Console.WriteLine("Index of P: " + result);
Console.ReadLine( );
}
}
}
输出
Index of I: 0 Index of P: -1
这里,
str.IndexOf('I')
- 返回0
,因为'I'
在 str 的索引0处str.IndexOf('P')
- 返回-1
,因为'P'
不在 str 中
示例 2:带起始索引的 IndexOf()
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
string str = "Ice cream";
int result;
// returns index of char I
result = str.IndexOf('I', 0);
Console.WriteLine("Index of I: " + result);
// returns -1
result = str.IndexOf('I', 2);
Console.WriteLine("Index of I: " + result);
Console.ReadLine( );
}
}
}
输出
Index of I: 0 Index of I: -1
在这个程序中,
str.IndexOf('I', 0)
- 从索引0开始搜索str.IndexOf('I', 2)
- 从索引2开始搜索
正如我们所见,str.IndexOf('I', 2)
返回 -1
,因为在索引2之后找不到 'I'
。
示例 3:带起始索引和计数的 IndexOf()
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
string str = "Ice cream";
int result;
// returns -1
result = str.IndexOf('m', 0, 1);
Console.WriteLine("Index of m: " + result);
// returns index of m
result = str.IndexOf('m', 0, 9);
Console.WriteLine("Index of m: " + result);
Console.ReadLine( );
}
}
}
输出
Index of m: -1 Index of m: 8
这里,
str.IndexOf('m', 0, 1)
- 从索引0开始,在1个字符内进行搜索str.IndexOf('m', 0, 9)
- 从索引0开始,在9个字符内进行搜索
正如我们所见,str.IndexOf('m', 0, 1)
返回 -1
,因为在索引0之后的1个字符内找不到 'm'
。