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;
}
}
- String index out of range: -1
- String index out of range: -1
- Java String index out of range: -1
- 【解决问题.思路篇】StringIndexOutOfBoundsException:String index out of range: -1
- 关于String index out of range: -1报错问题
- 由String index out of range: -1引发的思考
- String index out of range: 0
- Gradle:String index out of range: 0
- String index out of range: 0
- 遇到的一个"String index out of range" 问题
- python PIL, 错误:IndexError: string index out of range
- android release build error: String index out of range: -125
- poi处理excel的string index out of range -3
- 解决SSO客户端验证错误String index out of range
- java.lang.StringIndexOutOfBoundsException: String index out of range: 0
- list index out of range
- RangeError: index out of range
- list index out of range
- (转的)MFC打印预览 映射模式 坐标变换
- 用Fortran来实现DLL的编程和应用(2)
- gentoo安装步骤整理
- 我的blog开张了
- select 控件的动态操作方法
- String index out of range: -1
- 另一种树型结构的解决方案
- 在网站开发中经常用到的javaScript技术
- 用Fortran来实现DLL的编程和应用(3)
- 木马MicrosoftSQL.exe(Trojan-Downloader.Win32.VB.ajb/Trojan.DL.VB.cap)
- 苹果电脑创始人乔布斯:讲三个我自己的故事
- visual C++ 6.0开发工具与调试
- Oracle中null的使用详解
- 在 Windows 中实现 Java 本地方法