C# String IndexOf() 字符串索引查找方法
字符串 IndexOf()
方法返回指定字符/子字符串在字符串中首次出现的索引。
示例
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
string str = "Ice cream";
// 返回子字符串 cream 的索引
int result = str.IndexOf("cream");
Console.WriteLine(result);
Console.ReadLine();
}
}
}
// 输出:4
IndexOf() 语法
字符串 IndexOf()
方法的语法是:
String.IndexOf(string value, int startIndex, int count)
这里,IndexOf()
是 String
类的一个方法。
IndexOf() 参数
IndexOf()
方法接受以下参数:
- value - 要搜索的字符串
- startIndex - 搜索的起始位置
- count - 要检查的字符位置数量
IndexOf() 返回值
IndexOf()
方法返回:
- 指定字符/字符串首次出现的 索引
- 如果未找到指定字符/字符串,返回 -1
示例 1:C# 字符串 IndexOf()
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
string str = "Ice cream";
int result;
// 返回字符 'I' 的索引
result = str.IndexOf('I');
Console.WriteLine("I 的索引: " + result);
// 返回 -1
result = str.IndexOf('P');
Console.WriteLine("P 的索引: " + result);
Console.ReadLine( );
}
}
}
输出
I 的索引: 0
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;
// 返回字符 I 的索引
result = str.IndexOf('I', 0);
Console.WriteLine("I 的索引: " + result);
// 返回 -1
result = str.IndexOf('I', 2);
Console.WriteLine("I 的索引: " + result);
Console.ReadLine( );
}
}
}
输出
I 的索引: 0
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;
// 返回 -1
result = str.IndexOf('m', 0, 1);
Console.WriteLine("m 的索引: " + result);
// 返回 m 的索引
result = str.IndexOf('m', 0, 9);
Console.WriteLine("m 的索引: " + result);
Console.ReadLine( );
}
}
}
输出
m 的索引: -1
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'
。