我希望子数组已经在主数组中进行了测试。 但我得到错误。
我做的测试是对的还是需要加条件?
最后,我需要打印主数组的索引,其中子字符串开始。
回答示例:
String m="cd e";
String n="abcd efghi";
print>>>> 2(the index in n String)
错误:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: 4
at java.lang.String.charAt(Unknown Source)
at test1.main(test1.java:10)
代码:
String m="cd e";
String n="abcd efghi";
for (int i = 0; i < m.length(); i++) {
for (int j = 0; j < n.length(); j++) {
if(m.charAt(j)==n.charAt(i) )
if(m.charAt(j+1)==n.charAt(i+1))
System.out.println(i);
}
}
谢谢。
最佳答案
试试这个: 你看 n 是因为它的长度最长。我希望这有帮助。 String m="cd e"; String n="abcd efghi";
for (int i = 0; i < n.length(); i++) {
for (int j = 0; j <i; j++) {
if (i <= m.length()){ // to prevent indexoutOfbound exception
if(m.charAt(j)==n.charAt(i) ) {
System.out.println(m.charAt(j)+"-->"+i);
}
}
}
}
输出:
c-->2
d-->3
-->4
关于java - 字符串索引 - 子字符串和主字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37659407/