Java 如何使用char数组在没有String方法的情况下查找子字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22133615/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 13:49:13  来源:igfitidea点击:

How to find substring without String methods using char arrays?

javastringalgorithm

提问by user1659644

You are not allowed to use any inbuilt functions like indexOf(), contains()or matches() of String class.

不允许使用任何内置函数,例如String 类的indexOf(),contains()或matches() 。

Find string apple in string webapple using given char arrays?

使用给定的字符数组在字符串 webapple 中查找字符串 apple?

String webapple ="webapple";
String apple="apple";
char[] webappleArray=webapple.toCharArray();
char[] appleArray = apple.toCharArray();

write a function

写一个函数

public boolean isPresent(char[] apple ,char[] webapple ){
    //your code here 
}

采纳答案by libik

I add it here in case someone really need it or want to study from it:

我在这里添加它以防有人真的需要它或想从中学习:

public static void main(String[] args) {
    String webapple = "webapple";
    String apple = "apple";
    char[] webappleArray = webapple.toCharArray();
    char[] appleArray = apple.toCharArray();
    System.out.println(isPresent(appleArray, webappleArray));
}

public static boolean isPresent(char[] apple, char[] webapple) {
    for (int i = 0; i < webapple.length - apple.length+1; i++) {
        for (int j = 0; j < apple.length; j++) {
            if (webapple[i + j] == apple[j]) {
                if (j == apple.length - 1) {
                    return true;
                }
            } else {
                break;
            }
        }
    }
    return false;
}