【C#】IndexOf 干货用法

来源:互联网 发布:小米网络劫持怎么解决 编辑:程序博客网 时间:2024/05/20 08:41


每次都记不住IndexOf的用法,哎呀都要去网上先找,这次Mark一下,希望能记住~~~


* String.IndexOf 方法 (Char, Int32, Int32)
   报告指定字符在此实例中的第一个匹配项的索引。搜索从指定字符位置开始,并检查指定数量的字符位置。
* String.IndexOf(value, startIndex, count)

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


string str = "dfa人文ddfdfdf人文ddd";


string d1= str.IndexOf("U").ToString();//返回 -1------> 没有找到


string d2= str.IndexOf("人文").ToString();//返回 3---->找到出现的第一个位置

 
string d3= str.IndexOf("人文",5).ToString();//返回12说明:这是从第5个字符开始查起。 


string d4= str.IndexOf("邓",14,3).ToString();//返回 -1


string d5 = str.IndexOf("邓",15,3).ToString();//返回 -32 说明:从第15个字符开始查找,要查找的范围是从第15个字符开始后3个字符,即从第15,16,17,3个字符中查找。

=======================================================================================

* String.LastIndexOf 方法
   报告指定的 Unicode 字符或 String 在此实例中的最后一个匹配项的索引位置。


string str = "深圳市盈基实业有限公司国际通邓事文*深圳市盈基实业有限公司国际通邓事文";


Label1.Text = str.LastIndexOf("邓文").ToString();//返回-1


Label1.Text = str.LastIndexOf("邓").ToString();//返回32

Label1.Text = str.LastIndexOf("邓",8).ToString();//返回-1


Label1.Text = str.LastIndexOf("邓",20).ToString();//返回14


Label1.Text = str.LastIndexOf("邓",33).ToString();//返回32


说明:在指定的范围内查找字符,这个范围是上面的输入的参数,理解为,从索引0开始到指定的数值位置范围内查找最后一个匹配的的字符串的位置。示例中,0-8中没有“邓”字,所以返回-1,0-20范围中,有一个“邓”字在索引14位置上,0-33范围中有两个“邓”字,因为LastIndexOf是返回最后一个匹配项索引位置,所以返32,而不是14。

原创粉丝点击