LastIndexOf和java.lang.IndexOutOfBoundsException
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了LastIndexOf和java.lang.IndexOutOfBoundsException,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1584字,纯文字阅读大概需要3分钟。
内容图文
![LastIndexOf和java.lang.IndexOutOfBoundsException](/upload/InfoBanner/zyjiaocheng/668/2cccd87cbc644282a8ce420fb713c970.jpg)
我有一个字符串CCAATA CCGT,我正在尝试获取固定长度的连续子序列n.然后,我想得到这样的东西:
该字符串中每个子序列的索引. 0-3、1-4、2-5等.
0 thru 3 : CCAA
1 thru 4 : CAAT
2 thru 5 : AATA
3 thru 6 : ATAC
4 thru 7 : TACC
5 thru 8 : ACCG
6 thru 9 : CCGT
列表大小为7.在这里,我遍历列表并获取索引& lastIndexOf. 3点到6点之后:ATAC,我得到了
Exception in thread “main”
java.lang.IndexOutOfBoundsException: Index: 7, Size: 7
for (int i = 0; i < list.size(); i++) {
System.out.println(ss.indexOf(list.get(i))
+ " thru " + ss.lastIndexOf(list.get(i + n - 1)) + " : "
+ list.get(i));
演示:
import java.util.ArrayList;
public class Subsequences {
public static void main(String[] args) {
String s = "CCAATA CCGT";
ArrayList<String> list = new ArrayList<String>(); // list of subsequence
int n = 4; // subsequences of length
String ss = s.replaceAll("\\s+", "");
String substr = null;
for (int i = 0; i <= ss.length() - n; i++) {
substr = ss.substring(i, i + n);
list.add(substr);
}
for (int i = 0; i < list.size(); i++) {
System.out.println(ss.indexOf(list.get(i))
+ " thru " + ss.lastIndexOf(list.get(i + n - 1)) + " : "
+ list.get(i));
}
}
}
有什么提示吗?
解决方法:
您不需要将n添加到lastIndexOf中,因为您已将子字符串分隔为4.List中的每个条目都包含4个字符.将索引检查更改为此
(ss.lastIndexOf(list.get(i)) + n - 1)
最后看起来像这样
for (int i = 0; i < list.size(); i++) {
System.out.println(ss.indexOf(list.get(i))
+ " thru " + (ss.lastIndexOf(list.get(i)) + n - 1) + " : "
+ list.get(i));
}
输出:
0 thru 3 : CCAA
1 thru 4 : CAAT
2 thru 5 : AATA
3 thru 6 : ATAC
4 thru 7 : TACC
5 thru 8 : ACCG
6 thru 9 : CCGT
内容总结
以上是互联网集市为您收集整理的LastIndexOf和java.lang.IndexOutOfBoundsException全部内容,希望文章能够帮你解决LastIndexOf和java.lang.IndexOutOfBoundsException所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。