我已经通过Google的一些解决方案的帮助编写了代码。你能帮我详细了解while循环的细节吗?字符串和子字符串以及子字符串在主字符串中的存在次数
import java.util.Scanner;
public class TwoStringsWordRepeat {
public static void main(String[] args) {
Scanner s = new Scanner (System.in);
System.out.print("Enter Sentence: ");
String sentence = s.nextLine();
System.out.print("Enter word: ");
String word = s.nextLine();
int lastIndex = 0;
int count = 0;
while (lastIndex != -1) {
lastIndex = sentence.indexOf(word, lastIndex);
if (lastIndex != -1) {
count++;
lastIndex += word.length();
}
}
System.out.println(count);
}
}
向我解释while循环中的代码.indexOf();
。
indexOf()根据在urs的代码块中使用的变量,在'sentence'中找到'word'的第一个匹配项,在'lastIndex'位置开始搜索。 – Adarsh