String.LastIndexOf的经历

C#里的String类里有个LastIndexOf方法,其中一个重载方法
MSDN里这样描述:
public int LastIndexOf(
**** char **** value ,
**** int **** startIndex ,
**** int **** count
**);

**

Parameters

**value ** A Unicode character to seek. **startIndex ** The starting position of a substring within this instance. **count ** **The number of character positions to examine.

** 我在使用时,我想从字符串dd/fff/fff/>的子串dd/fff/fff里找到最后一个“/”,即倒数第二个“/”于是:
string strTest=”dd/fff/fff/>”;
int iPos=strTest.LastIndexOf('/',0,strTest.Length-2);
但是在执行时老是报“ArgumentOutOfRangeException”的错误,后来想到了,原来LastIndexOf方法检查字符串的方向是从右向左的,因此,要以右边为基准:
int iPos=strTest.LastIndexOf('/',strTest.LastIndexOf('/')-1,strTest.Length-2);

平时都是以左边为开始的,所以碰到逆向思维时,很容易出错!

Published At
Categories with Web编程
Tagged with
comments powered by Disqus