获取字符串中子串或字符的索引值

IndexOf() 方法

定义:查找字符串中指定字符或字串首次出现的位置,返回索引值。该方法区分大小写。

功能:在字符串中从前向后定位字符和字符串,返回值是指定的字符在字符串中的绝对位置,如没有查到指定的字符则该方法返回-1。注意:字符串位置从0开始计算。

重载形式:

      定位字符    

  • 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 dic = "asdfghjk";

dic.IndexOf("d");// = 2

dic.IndexOf("e");// = -1

dic.IndexOf("j",5); // = 6 从前往后,从第五位开始定位j第一次出现的位置

dic.IndexOf("j",5,2);// = 6 从前往后,从第五位开始查,查二位(即从第五位到第六位),定位j

LastIndexOf()方法

功能:查找字串中指定字符或字串最后出现的位置,返回索引值

IndexOfAny() ||lastindexofany()

功能:接受字符数组做为变元,其他方法同上,返回数组中任何一个字符最早||最晚出现的下标位置

例如:

char[] array = {'s','d','k'};

string ss = "asdfghjkl";

Response.Write(ss.IndexOfAny(array))=1;

Response.Write(ss.IndexOfAny(array,5))=7;

Response.Write(ss.IndexOfAny(array,5,2))=-1;

 

posted @ 2017-03-25 22:45  雷雨天的雷胖子  阅读(9497)  评论(0编辑  收藏  举报