c#中slice,substr,substring区别

1. 都使用一个参数:

//栗子数据
var arr = [1,2,3,4,5,6,7],
str = "helloworld!"; //防止空格干扰,不用带空格的,注意这里有个!号也算一位

console.log(str.slice(1)); //elloworld!
console.log(str.substring(1)); //elloworld!
console.log(str.substr(1)); //elloworld!

console.log(arr.slice(1)); //[2,3,4,5,6,7]
console.log(arr.substr(1)); //TypeError: arr.substr is not a function
console.log(arr.substring(1)); //TypeError: arr.substring is not a function
结论一目了然,都是从指定位置截到结束,而数组是没有substr和substring方法的!!!(初学者谨记!包含str的,当然是字符串专用!)因此后面的内容,数组将不会再使用这两个方法。

2. 都使用两个正数参数(第一个小于第二个):

//栗子不变
console.log(str.slice(1,4)); //ell
console.log(str.substring(1,4)); //ell
console.log(str.substr(1,4)); //ello 不一致了!!!

console.log(arr.slice(1,4)); //[2,3,4]
区别出现了,substr的结果不一致,因为substr的第二参数,是截取几位的意思,而其他两个的是截取到第几位的前面(之所以这么说,是因为不包括这个位置)。数组字符串表现一致。

3. 都使用两个正数参数(第一个大于第二个):

//栗子不变
console.log(str.slice(5,1)); //""
console.log(str.substring(5,1)); //ello
console.log(str.substr(5,1)); //"w"

console.log(arr.slice(5,1)); //[]
区别又出现了,除了slice,其他都有值。也就是说,substring会将此情况的位置自动调换,然后截取出相应的值;substr当然按照原意从第5个位置开始,截取1位返回一个字符;而slice直接返回空,slice的第一参数必须要小于等于第二参数才有效,这是顺序的感觉。

4. 使用一正一负两个参数(第一正,第二负)

//栗子不变
console.log(str.slice(1,-2)); //elloworl
console.log(str.substr(1,-2)); //""
console.log(str.substring(1,-2)); //h

console.log(arr.slice(1,-2)); //[ 2, 3, 4, 5]
可见,slice第二参数为负数时,是从尾部倒数来计算或者说是与字符串或数组的长度相加得出的结果来计算;而substring, 无论第二参数是负多少,都只截取了第一个字符;substr同样,个数不可能是负数,所以是空;总结substring和substr第二参数为负数时其实是无效果的。

5. 使用一正一负两个参数(第一负,第二正)

//栗子不变
console.log(str.slice(-3,1)) //""
console.log(str.substr(-3,1)) //l
console.log(str.substring(-3,1)) //h

console.log(arr.slice(-3,1)) //[]
这里还是一正一负,只不过换了位置,然而结果确不同了。slice结果是空,这个结合第3和第4种情况,可知,这个实际是slice(8,1),第一参数大于第二参数了,所以是无效的,空值;substring,结合第3和第4种情况,是调换了顺序,但是还是负数,依然也是无效的,只返回第一个字符;substr,第一参数负数同样代表从尾部倒数或者字符串的长度相加得出的结果来计算,等同于substr(8,1),截取栗子中的一位,得到了“l”。

6. 全负数(两种情况合一)

//栗子不变
console.log(str.slice(-1,-5));
console.log(str.substr(-1,-5));
console.log(str.substring(-1,-5));

console.log(arr.slice(-1,-5));
//上面的结果全是空

console.log(str.slice(-5,-1)); //orld
console.log(str.substr(-5,-1)); //""
console.log(str.substring(-5,-1)); //""

console.log(arr.slice(-5,-1)); //[ 3, 4, 5, 6 ]
这两种情况合一了,其实这个也多余说了,只不过是为了把情况都列出来而已,因为上述的结果都可以用第1到第5种情况解释完全的,大家自行换算一下就知道了,结论是一样的。由此也提醒,主要是初学者,需要注意的就是负数的情况,因为有时候会突然转不过来弯。

总结一下:

1.  slice,substring,substr 都是用来截取字符串或数组的,然而数组只能使用slice,这三者如果不传参数,则都返回全部内容;

2.  参数为正数时,只有substring会自动调换顺序,slice在第一参数大于第二参数时会无效返回空,而substr无所谓,除非给定的第一参数超出了源数据长度才会返回空;

3. 参数为负数时,只有substring会永远无效,即不要给substring使用负值!slice可认为从尾部倒数,或者直接用源数据长度加上这个负值换算为正数,然后结论依然遵循第2条所述;而substr,则只适用第一参数为负数,换算方法同slice,其第二参数代表截取的个数,是不能为负数的;

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值