C# String.IndexOf 方法

     转载 。。。。。。

  String.IndexOf 方法 (value, [startIndex], [count])

  报告指定字符在此实例中的第一个匹配项的索引。搜索从指定字符位置开始,并检查指定数量的字符位置。

  参数

  value

  要查找的 Unicode 字符。 对 value 的搜索区分大小写。

  startIndex(Int32)

  可选项,搜索起始位置。不设置则从0开始。

  count(Int32)

  可选项,要检查的字符位数。

  返回值

  如果找到该字符,则为 value 的索引位置;否则如果未找到,则为 -1。

  IndexOf()

  查找字串中指定字符或字串首次出现的位置,返首索引值,如:

  str1.IndexOf("字"); //查找“字”在str1中的索引值(位置)

  str1.IndexOf("字串");//查找“字串”的第一个字符在str1中的索引值(位置)

  str1.IndexOf("字",start,end);//从str1第start+1个字符起,查找end个字符,查找“字”在字符串STR1中的位置[从第一个字符算起]注意:start+end不能大于str1的长度

  indexof参数为string,在字符串中寻找参数字符串第一次出现的位置并返回该位置。如string s="0123dfdfdf";int i=s.indexof("df");这时i==4。

  如果需要更强大的字符串解析功能应该用Regex类,使用正则表达式对字符串进行匹配。

  indexof() :在字符串中从前向后定位字符和字符串;所有的返回值都是指在字符串的绝对位置,如为空则为- 1

  string test="asdfjsdfjgkfasdsfsgfhgjgfjgdddd";

  test.indexof('d') =2 //从前向后 定位 d 第一次出现的位置

  test.indexof('d',1) =2 //从前向后 定位 d 从第三个字符串 第一次出现的位置

  test.indexof('d',5,2) =6 //从前向后 定位 d 从第5 位开始查,查2位,即 从第5位到第7位;

  lastindexof() :在字符串中从后向前定位字符和字符串;、

  用法和 indexof() 完全相同。

  下面介绍 IndexOfAny ||lastindexofany

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

  如下

  char[] bbv={'s','c','b'};

  string abc = "acsdfgdfgchacscdsad";

  Response.Write(abc.IndexOfAny(bbv))=1

  Response.Write(abc.IndexOfAny(bbv, 5))=9

  Response.Write(abc.IndexOfAny(bbv, 5, 3))=9

  lastindexofany 同上。

语法

  stringObject.indexOf(searchvalue,fromindex)

参数  
   
   

描述searchvalue必需。规定需检索的字符串值。fromindex可选的整数参数。规定在字符串中开始检索的位置。它的合法取值是 0 到 stringObject.length - 1。如省略该参数,则将从字符串的首字符开始检索。

说明

  该方法将从头到尾地检索字符串 stringObject,看它是否含有子串 searchvalue。开始检索的位置在字符串的fromindex 处或字符串的开头(没有指定 fromindex 时)。如果找到一个 searchvalue,则返回 searchvalue的第一次出现的位置。stringObject 中的字符位置是从 0 开始的。

实例

  在本例中,我们将在

)
)

  

  

"Hello world!" 字符串内进行不同的检索:
  
<script type="text/javascript">  var str="Hello world!"  document.write(str.indexOf("Hello") +"<br />"  document.write(str.indexOf("World") +"<br />"  document.write(str.indexOf("world"))
  
</script>以上代码的输出:
  
0-16

原文地址:https://www.cnblogs.com/weixing/p/2010108.html