java—使用嵌套循环在另一个字符串中出现一个字符串

rslzwgfq  于 2021-06-30  发布在  Java
关注(0)|答案(2)|浏览(396)

要求只使用循环而不是构造函数或数组的练习对所有使用数组和构造函数的站点都有帮助。我花了一个星期的时间研究代码,研究了大量的试验,寻找类似的问题集,但都有帮助,没有达到最后一步输入:字符串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);
kmynzznz

kmynzznz1#

找到后,需要跳过找到的文本。
因为循环 i++ ,这意味着:

if (found) {
    res++;
    i += text1.length() - 1;
}

更新
另外,如果子字符串位于字符串的末尾,代码将找不到它,因为外循环结束得早,所以请更改 <<= :

for (int i = 0; i <= text2.length() - text1.length(); i++) {
mcdcgff0

mcdcgff02#

你就快到了。通过以下更改,您的代码将按预期工作:
增量 itext1.length() - 1 每次 text1 找到并 j == text1.length() . 在你增加之后 itext1.length() - 1 ,循环的增量部分将递增 i1 这将导致 i 递增的 text1.length() .
从修改条件 i < text2.length() - text1.length()i < text2.length() .
从修改条件 j<text1.length() && foundj < 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

相关问题