我需要有人详细说明此代码的某些部分。
class ContinueWithLabelDemo {
public static void main(String[] args) {
String searchMe = "Look for a substring in me";
String substring = "sub";
boolean foundIt = false;
int max = searchMe.length() -
substring.length();
test:
for (int i = 0; i <= max; i++) {
int n = substring.length();
int j = i;
int k = 0;
while (n-- != 0) {
if (searchMe.charAt(j++) != substring.charAt(k++)) {
continue test;
}
}
foundIt = true;
break test;
}
System.out.println(foundIt ? "Found it" : "Didn't find it");
}
}
更具体地说,我不明白这部分:
int n = substring.length();
int j = i;
int k = 0;
while (n-- != 0) {
if (searchMe.charAt(j++) != substring.charAt(k++)) {
continue test;
}
}
为什么有必要在这段代码中声明 j 和 k ?我知道 if 语句是有原因的
if (searchMe.charAt(j++) != substring.charAt(k++))
但我不明白这部分代码实际上在做什么。
另外,什么是
while (n-- != 0)
意思是?
最佳答案
while (n-- != 0)
这只是循环,每次循环时将 n 减 1,当 n(之前)减 1 不为 0 时结束。
int n = substring.length();
int j = i;
int k = 0;
while (n-- != 0) {
if (searchMe.charAt(j++) != substring.charAt(k++)) {
continue test;
}
}
这段代码从字符串中不同位置的 j 和 k 开始,然后循环比较字符串中该位置的字符。 j++ 只是说“使用 j 的当前值,然后加 1”。
关于java - 需要帮助理解本类(class)的部分内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20831028/