String index out of range: -1

来源:互联网 发布:淘宝客高佣api 编辑:程序博客网 时间:2024/04/30 06:49

      前两天报字符串越界,查找中发现,应该是取某一个字符的位置时,出错了,原来使用lastIndexOf时要取得这个字符在被查找的字符串里没有。

解决方法,在取位置之前,先要验证一下,字符是否存在。

 if(name.lastIndexOf("Form")!=-1){

      name = name.substring(0, name.lastIndexOf("Form"));

}

JScript  语言参考

 

--------------------------------------------------------------------------------

lastIndexOf 方法
返回 String 对象中子字符串最后出现的位置。

strObj.lastIndexOf(substring[, startindex])

参数
strObj

必选项。String 对象或文字。

substring

必选项。要在 String 对象内查找的子字符串。

startindex

可选项。该整数值指出在 String 对象内进行查找的开始索引位置。如果省略,则查找从字符串的末尾开始。

说明
lastIndexOf 方法返回一个整数值,指出 String 对象内子字符串的开始位置。如果没有找到子字符串,则返回 -1。

如果 startindex 是负数,则 startindex 被当作零。如果它比最大字符位置索引还大,则它被当作最大的可能索引。

从右向左执行查找。否则,该方法和 indexOf 相同。

下面的示例说明了 lastIndexOf 方法的用法:

function lastIndexDemo(str2)
{
   var str1 = "BABEBIBOBUBABEBIBOBU"
   var s = str1.lastIndexOf(str2);
   return(s);
}

在java类中使用,大体上差不多。

 以下摘自http://www.chinageren.com/jc/HTML/115914_2.html

DateBean.java
{
   private String dateStr;
   private String year;
   private String month;
   private String day;
   //
   public void setDateStr(String str)    //私有变量dateStr的set方法
   {
     this.dateStr=str;
   }
   public String getDateStr()    //私有变量dateStr的get方法
   {
     return dateStr;
   }
   public String getYear()//得到年的字符串
   {
     int a=dateStr.indexOf("-");//求第一个“-”的位数
     year=dateStr.substring(0,a);//取第一个“-”前的字符串
     return year;
   }
   public String getMonth()//得到月的字符串
   {
     int a=dateStr.indexOf("-");//求第一个“-”的位数
     int b=dateStr.lastIndexOf("-");//求最后一个“-”的位数
     month=dateStr.substring(a+1,b);//取两个“-”之间的字符串
     return month;
   }
   public String getDay()//得到日的字符串
   {
     int b=dateStr.lastIndexOf("-");//求最后一个“-”的位数
     int len=dateStr.length();//求字符串的长度
     day=dateStr.substring(b+1,len);//取最后一个“-”以后的字符串
     return day;
   }
}