Java 使用嵌套循环在另一个字符串中出现的字符串
要求只使用循环而不是构造函数或数组的练习对所有使用数组和构造函数的站点都有帮助。 我花了一周的时间来理解代码,研究了大量的试验,并寻找类似的问题集,但都是帮助,没有达到最后一步 输入: 字符串1:ooo 弦乐2:呜呜呜 输出: 那不正确 输出必须是(3) 我的代码在所有输入字符串中工作,但在重复字母中不正确Java 使用嵌套循环在另一个字符串中出现的字符串,java,loops,Java,Loops,要求只使用循环而不是构造函数或数组的练习对所有使用数组和构造函数的站点都有帮助。 我花了一周的时间来理解代码,研究了大量的试验,并寻找类似的问题集,但都是帮助,没有达到最后一步 输入: 字符串1:ooo 弦乐2:呜呜呜 输出: 那不正确 输出必须是(3) 我的代码在所有输入字符串中工作,但在重复字母中不正确 Scanner input = new Scanner(System.in); String text1 = input.nextLine(); String tex
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);
扫描仪输入=新扫描仪(System.in);
字符串text1=input.nextLine();
字符串text2=input.nextLine();
int res=0;
对于(int i=0;i您就快到了。通过以下更改,您的代码将按预期工作:
每次找到text1
并且j==text1.length()
时,通过text1.length()-1
增加i
。在通过text1.length()-1
增加i
之后,将通过1
增加i
,这将导致i
增加text1.length()
将条件从i
修改为i
从j修改条件找到后,需要跳过找到的文本
由于循环执行i++
,这意味着:
if(已找到){
res++;
i+=text1.length()-1;
}
更新
另外,如果子字符串位于字符串的末尾,代码将找不到它,因为外部循环结束得很早,所以更改谢谢您的帮助,但是当我检查输入时:字符串1:string2:studentsth正在使用-output:3不正确的硬件ct输出必须是4。@MohamedElkady-我已经更新了答案。我试图继续这门课程,并且我开始继续这门课程以理解这个问题集。非常欢迎。祝你成功!你能帮助所有像我这样的访问者找到这个解决方案,并提供精确的算法来实现这个想法。输入将失败,字符串1:“
和字符串2:学生在
@ArvindKumarAvinash的实验室里努力学习。@Andreas你能制定你的解决方案和流程图来研究和测试错误吗?”。thanks@MohamedElkady哈?你请求帮助找出你的代码出了什么问题,这个答案涵盖了全部内容。斯塔科夫erflow不是一个教学网站,所以我不知道你还想问什么。如果你想要一个流程图,请画一个。@Andreas这个程序成为我或任何人的学习途径,如果有很多讨论,我们将学到更多的信息和技术。谢谢
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