我必须打印找到模式的索引。就像如果字符串 = "ABCABCDEABCDEA" 和模式 = "ABCD" 一样,输出将是 4 和 9



这是我写的代码,它给出了错误的输出。我必须在找到图案的地方打印索引。比如if string = "ABCABCDEABCDEA"和pattern = "ABCD",输出将是4和9

让我来讨论一下它的方法-我想要的是如果字符串的第i个元素等于模式的第0个元素。然后进入循环,检查图案,长度。其他的继续。

public class Word_check {
public static void main(String[] args) {
// TODO Auto-generated method stub
String str1="ABCDAFGFGFABCDKLHKHABCD";
String tocheck="ABCD";
boolean isfound=false;
int count=0;
for(int i=0;i<str1.length();i++) {

if(str1.charAt(i)==tocheck.charAt(count)){

for(int j=i;j<tocheck.length();j++) {

if(str1.charAt(j)==tocheck.charAt(count)) {

isfound=true;
}
else {
isfound=false;
break;
}
count++;
}
if(isfound==true) {
System.out.println(i+1);
}

}
else {
continue;
}
count=0;
}
}

}

试试这个-

public static void main(String[] args) {
// TODO Auto-generated method stub
String str1="ABCDAFGFGFABCDKLHKHABCD";
String tocheck="ABCD";
int lastIndex = str1.indexOf(tocheck);
while (lastIndex != -1){
System.out.println(lastIndex);
lastIndex = str1.indexOf(tocheck, lastIndex + 1);
}
}

从您的示例中我看到您想要打印index + 1(在java索引从0开始,因此程序应该打印3和8)。如果是这种情况,只需执行System.out.println(lastIndex + 1);

正如@Stultuske所写,使用indexOf():

var index = str1.indexOf("ABCD");
while (index >= 0) {
System.out.println(index);
index = str1.indexOf("ABCD", index + 1);
}

最新更新