【发布时间】:2018-04-02 10:28:42
【问题描述】:
我在 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() 查找
word在sentence中的第一个匹配项,根据urs 代码块中使用的变量从位置lastIndex开始搜索。