要求只使用循环而不是构造函数或数组的练习对所有使用数组和构造函数的站点都有帮助。我花了一个星期的时间研究代码,研究了大量的试验,寻找类似的问题集,但都有帮助,没有达到最后一步输入:字符串1:ooo字符串2:woooooooo
输出: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);
2条答案
按热度按时间kmynzznz1#
找到后,需要跳过找到的文本。
因为循环
i++
,这意味着:更新
另外,如果子字符串位于字符串的末尾,代码将找不到它,因为外循环结束得早,所以请更改
<
至<=
:mcdcgff02#
你就快到了。通过以下更改,您的代码将按预期工作:
增量
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
.示例运行: