首 页IT知识库收藏内容
当前位置:翔宇亭IT乐园IT知识库C#C#基础

C#中指定搜索起始位置和搜索字符数的字符搜索函数IndexOf

减小字体 增大字体 作者:本站  来源:本站整理  发布时间:2012-06-17 11:39:59

我们在搜索一个字符串中是否包含一个指定的字符时,可以指定被搜索字符串中的起始位置,所涉及的函数原型如下:

public int IndexOf( char value, int startIndex, int count )

这个方法有三个参数,第一个参数指定要搜索的字符值,第二个参数指定搜索的起始位置,count指定搜索的字符数。

其返回值有两种情况,如果搜索到了指定的字符,则返回该字符从0开始的位置值,否则返回-1。

下面是一个例子:

string str = "翔宇亭IT乐园欢迎您。";
int iPos1 = str.IndexOf('I', 2, 1);
int iPos2 = str.IndexOf('I', 5, 3);
int iPos3 = str.IndexOf('I',1, 2);
int iPos4 = str.IndexOf('I',1, 3);
int iPos5 = str.IndexOf('I', 5, 7);

上面的例子中,iPos1=-1,iPos2 = -1,iPos3 = -1, iPos4 = 3,而int iPos5这一行将引发异常,原因是给定的第三个参数值7,超出了字符串的索引(从索引5往后数7个位置,不存在)。

IndexOf方法还有其它八种重载形式:

(1)public int IndexOf(char value)

(2)public int IndexOf(char value, int startIndex)

(3)public int IndexOf( string value, int startIndex)

(4)public int IndexOf(string value,StringComparison comparisonType )

(5)public int IndexOf(string value )

(6)public int IndexOf(string value,int startIndex,int count )

(7)public int IndexOf(string value,int startIndex,StringComparison comparisonType )

(8)public int IndexOf(string value,int startIndex,int count, StringComparison comparisonType )

微信搜索“优雅的代码”关注本站的公众号,或直接使用微信扫描下面二维码关注本站公众号,以获取最新内容。

个人成长离不开各位的关注,你的关注就是我继续前行的动力。

知识评论评论内容只代表网友观点,与本站立场无关!

   评论摘要(共 0 条,得分 0 分,平均 0 分) 查看完整评论
愿您的精彩评论引起共鸣,带来思考和价值。
用户名: 查看更多评论
分 值:100分 90分 80分 70分 60分 40分 20分
内 容:
验证码:
关于本站 | 网站帮助 | 广告合作 | 网站声明 | 友情连接 | 网站地图
本站部分内容来自互联网,如有侵权,请来信告之,谢谢!
Copyright © 2007-2024 biye5u.com. All Rights Reserved.