C# IndexOf、LastIndexOf、IndexOfAny,LastIndexOfAny

来源:互联网 发布:linux 清空屏幕 编辑:程序博客网 时间:2024/06/06 06:52

string.IndexOf/string.LastIndexOf

IndexOf方法用于搜索在一个字符串中,某个特定的字符或者子串第一次出现的位置,该方法区分大小写,并从字符串的首字符开始以0计数。如果字符串中不包含这个字符或子串,则返回-1


定位字符:
int IndexOf(char value)
int IndexOf(char value, int startIndex)
int IndexOf(char value, int startIndex, int count)

定位子串:
int IndexOf(string value)
int IndexOf(string value, int startIndex)
int IndexOf(string value, int startIndex, int count)

在上述重载形式中,其参数含义如下:
value:待定位的字符或者子串。
startIndex:在总串中开始搜索的其实位置。
count:在总串中从起始位置开始搜索的字符数

例如:

string str = "那么骄傲少爷的身子跑堂儿的命儿那么骄傲少爷的身子跑堂儿的命儿";
string str1 = str.IndexOf("百度").ToString();          //返回 -1
string str2 = str.IndexOf("少爷").ToString();          //返回 4
string str3 = str.IndexOf("少爷", 10).ToString();     //返回19 说明:这是从第10个字符开始查起。
string str4 = str.IndexOf("爷", 10, 5).ToString();     //返回 -1
string str5 = str.IndexOf("爷", 10, 20).ToString();   //返回 20 说明:从第10个字符开始查找,要查找的范围是从第10个字符开始后20个字符,即从第10-30个字符中查找。

同IndexOf类似,LastIndexOf用于搜索在一个字符串中,某个特定的字符或者子串最后一次出现的位置,其方法定义和返回值都与IndexOf相同,不再赘述。

 

IndexOfAny/LastIndexOfAny
IndexOfAny方法功能同IndexOf类似,区别在于,它可以搜索在一个字符串中,出现在一个字符数组中的任意字符第一次出现的位置。同样,该方法区分大小写,并从字符串的首字符开始以0计数。如果字符串中不包含这个字符或子串,则返回-1。常用的IndexOfAny重载形式有3种:

int IndexOfAny(char[]anyOf);
int IndexOfAny(char[]anyOf, int startIndex);
int IndexOfAny(char[]anyOf, int startIndex, int count)。
在上述重载形式中,其参数含义如下:
anyOf:待定位的字符数组,方法将返回这个数组中任意一个字符第一次出现的位置。
startIndex:在原字符串中开始搜索的其实位置。
count:在原字符串中从起始位置开始搜索的字符数。

例如:

String s = "Hello";
char[] anyOf = { 'H', 'e', 'l' };
int i1 = s.IndexOfAny(anyOf);       //返回 0
int i2 = s.LastIndexOfAny(anyOf);   //返回 3

同IndexOfAny类似,LastIndexOfAny用于搜索在一个字符串中,出现在一个字符数组中任意字符最后一次出现的位置

0 0
原创粉丝点击