C#使用IndexOf、LastIndexOf、IndexOfAny、LastIndexOfAny在字符串中查找某个字符或字符串

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

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

以上2个方法用法几乎相同,只是用途有差异,常用的重载形式如下所示:

.

定位字符:

int IndexOf/LastIndexOf (char value)
int IndexOf/LastIndexOf(char value, int startIndex)
int IndexOf/LastIndexOf(char value, int startIndex, int count)

定位字符串:

int IndexOf/LastIndexOf(string value)
int IndexOf/LastIndexOf(string value, int startIndex)
int IndexOf/LastIndexOf(string value, int startIndex, int count)

其参数含义如下:

value:待定位的字符或者字符串。
startIndex:在原字符串中开始搜索的起始位置。
count:在原字符串中从起始位置开始搜索的字符数。

三、IndexOfAny
搜索在一个字符串中,出现在一个字符数组中的任意字符第一次出现的位置,该方法区分大小写,并从字符串的首字符开始以0计数。如果字符串中不包含这个字符或子串,则返回-1。

四、LastIndexOfAny
搜索在一个字符串中,出现在一个字符数组中任意字符最后一次出现的位置。

以上2个方法用法也几乎相同,只是用途有差异,常用的重载形式如下所示:

int IndexOfAny/LastIndexOfAny(char[]anyOf)
int IndexOfAny/LastIndexOfAny(char[]anyOf, int startIndex)
int IndexOfAny/LastIndexOfAny(char[]anyOf, int startIndex, int count)

参数含义如下:

anyOf:待定位的字符数组,方法将返回这个数组中任意一个字符第一次出现的位置。
startIndex:在原字符串中开始搜索的起始位置。
count:在原字符串中从起始位置开始搜索的字符数。

举个例子,我用IndexOfAny判断一个字符串中是否包含一些指定的特殊符号:

char[] specialChar = "`~!!@#$¥%^&*()()+=-{}[]【】、|;;::‘’'\" <>《》,,.。??/—".ToCharArray();
string content = "我是一个*数据[库]表";
int specialNum = content.IndexOfAny(specialChar);
if (specialNum > -1)
{
    Console.WriteLine("数据库表不能包括特殊字符");
}