086中国电影,chyna是擂台之王,近藤美佐
定位子串是指在一个字符串中寻找其中包含的子串或者某个字符。在string类中,常用的定位子串和字符的方法包括indexof/lastindexof及indexofany/lastindexofany,下面进行详细介绍。
1.indexof/lastindexof
indexof方法用于搜索在一个字符串中,某个特定的字符或者子串第一次出现的位置,该方法区分大小写,并从字符串的首字符开始以0计数。如果字符串中不包含这个字符或子串,则返回-1。常用的重载形式如下所示。
(1)定位字符:
int indexof(char value)
int indexof(char value, int startindex)
int indexof(char value, int startindex, int count)
(2)定位子串:
int indexof(string value)
int indexof(string value, int startindex)
int indexof(string value, int startindex, int count)
在上述重载形式中,其参数含义如下:
value:待定位的字符或者子串。
startindex:在总串中开始搜索的其实位置。
count:在总串中从起始位置开始搜索的字符数。
下面的代码在“hello”中寻找字符‘l'第一次出现的位置。
代码4-7 使用indexof寻找字符第一次出现位置:default.aspx.cs
1. string s=”hello”;
2. int i = s.indexof(‘l')); //2
同indexof类似,lastindexof用于搜索在一个字符串中,某个特定的字符或者子串最后一次出现的位置,其方法定义和返回值都与indexof相同,不再赘述。
2.indexofany/lastindexofany
indexofany方法功能同indexof类似,区别在于,它可以搜索在一个字符串中,出现在一个字符数组中的任意字符第一次出现的位置。同样,该方法区分大小写,并从字符串的首字符开始以0计数。如果字符串中不包含这个字符或子串,则返回-1。常用的indexofany重载形式有3种:
(1)int indexofany(char[]anyof);
(2)int indexofany(char[]anyof, int startindex);
(3)int indexofany(char[]anyof, int startindex, int count)。
在上述重载形式中,其参数含义如下:
(1)anyof:待定位的字符数组,方法将返回这个数组中任意一个字符第一次出现的位置。
(2)startindex:在原字符串中开始搜索的其实位置。
(3)count:在原字符串中从起始位置开始搜索的字符数。
下例在“hello”中寻找字符‘l'第一次和最后一次出现的位置。
代码4-8 使用indexofany寻找子串第一次和最后一次出现位置:default.aspx.cs
1. string s = “hello”;
2. char[] anyof={'h','e','l'};
3. int i1 = s.indexofany(anyof)); //0
4. int i2 = s.lastindexofany(anyof)); //3
同indexofany类似,lastindexofany用于搜索在一个字符串中,出现在一个字符数组中任意字符最后一次出现的位置。
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
Blazor server side 自家的一些开源的, 实用型项目的进度之 CEF客户端
.NET IoC模式依赖反转(DIP)、控制反转(Ioc)、依赖注入(DI)
vue+.netcore可支持业务代码扩展的开发框架 VOL.Vue 2.0版本发布
网友评论