How to know if a given string is substring from another string in Java

后端 未结 16 1748
情歌与酒
情歌与酒 2020-12-20 18:58

Hi I have to compute if a given string is substring of a bigger string. For example

String str = \"Hallo my world\";
String substr = \"my\"
<
16条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-20 19:28

        public boolean isSubString(String smallStr, String largerStr) {
        char[] larger = largerStr.toCharArray();
        char[] smaller = smallStr.toCharArray();
    
        int i = 0;
    
        for (int j = 0; j < larger.length; j++) {
            if(larger[j] == smaller[i]){
                if(i == smaller.length -1){
                    //done we found that this string is substring
                    return true;
                }
                i++;
                continue;
            }else{
                if(i > 0){
                    //that means we encountered a duplicate character before and if string was substring 
                    // it shouldn't have hit this condition..
                    if(larger.length - j >= smaller.length){
                        i = 0;
                        //reset i here because there are still more characters to check for substring..
                    }else{
                        //we don't have enough characters to check for substring.. so done..
                        return false;
                    }
    
                }
            }
    
        }
    
        return false;
    }
    

提交回复
热议问题