该练习要求仅使用循环而不使用构造函数或阵列,这在使用数组和构造函数的所有站点上均提供了所有帮助。我花了一个星期的时间到达代码,研究了大量的试验,寻找相似的问题集,但都没有帮助,没有达到最后一步的输入:字符串1:哦,字符串2:哦,哦
输出:7不正确
输出必须是(3)我的代码在所有字符串输入中均有效,但在重复的字母上不正确
Scanner input = new Scanner(System.in);
String text1 = input.nextLine();
String text2 = input.nextLine();
int res = 0;
for (int i=0;i<text2.length()-text1.length();i++)
{
if (text1.charAt(0) == text2.charAt(i))
{
boolean found = true;
for (int j=0;j<text1.length() && found;j++)
if (text1.charAt(j) != text2.charAt(i+j))
found = false;
if (found)
res++;
}
}
System.out.println(res);
你快到了。经过以下更改,您的代码将按预期工作:
i
由text1.length() - 1
每次text1
被发现,j == text1.length()
。递增i
后text1.length() - 1
,循环的递增部分将递增i
,1
导致i
递增text1.length()
。i < text2.length() - text1.length()
为i < text2.length()
。j<text1.length() && found
为j < text1.length() && found && i + j < text2.length()
。您也可以通过在条件text1.charAt(j) != text2.charAt(i + j)
变为时中断内部循环来提高程序的效率true
。
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the substring: ");
String text1 = input.nextLine();
System.out.print("Enter the string to search into: ");
String text2 = input.nextLine();
int res = 0;
for (int i = 0; i < text2.length(); i++) {
if (text1.charAt(0) == text2.charAt(i)) {
boolean found = true;
int j;
for (j = 0; j < text1.length() && found && i + j < text2.length(); j++) {
if (text1.charAt(j) != text2.charAt(i + j)) {
found = false;
break;
}
}
if (j == text1.length() && found) {
res++;
i += text1.length() - 1;
}
}
}
System.out.println(res);
}
}
运行示例:
Enter the substring: ooo
Enter the string to search into: Wooooooooow
3
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句