600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > C#中indexof和substring函数用法 (截取字符串)

C#中indexof和substring函数用法 (截取字符串)

时间:2024-01-23 16:24:13

相关推荐

C#中indexof和substring函数用法 (截取字符串)

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 同上。

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

substring() 用法

string a="aadsfdjkfgklfdglfd"

a.substring(5) //截取从第五位以后的所有字符串

a.substring(0,5) //截取从第0位置开始长度为5的字符串

如下例:

static void SplitPath(string fullName, out string fileName, out string ext){int i = fullName.IndexOf(".");fileName = fullName.Substring(0, i);ext = fullName.Substring(i+1);}static void Main2() {string fileName;string ext;SplitPath("index.html", out fileName, out ext);Console.WriteLine(fileName);Console.WriteLine(ext);}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。