How to know if a given string is substring from an

2020-02-14 02:18发布

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"

The method "contains" should return true because str contains substr (false otherwise).

I was looking for something like "contains" at the String class but I didn't find it. I suppose that the only solution is to use pattern matching. If this is the case which would be the better (cheapest) way to do this?

Thanks!

15条回答
爷的心禁止访问
2楼-- · 2020-02-14 02:52
public class StringIsSubString {

    public static void main(String[] args) {

        String s1 = "wel";
        String s2 = "12wlecome123";

        boolean isSubStr = isSubStr(s1,s2);
        System.out.println(isSubStr);
    }

    private static boolean isSubStr(String s1, String s2) {
        String s3 = "";
        int j = 0;

        if(s1.length() > s2.length()) {
            return false;
        } else if(s1.equals(s2)){
            return true;
        } else {
            for(int i=0; i<s1.length();i++) {
                for(; j<s2.length();j++) {
                    if(s1.charAt(i) == s2.charAt(j)) {
                        s3 = s3 + s1.charAt(i);
                        break;
                    }
                }
            }
            if(s3.equals(s1)) {
                return true;
            }
            return false;       
        }
    }
}
查看更多
姐就是有狂的资本
3楼-- · 2020-02-14 02:54
    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;
}
查看更多
太酷不给撩
4楼-- · 2020-02-14 03:00

I think there is a String function that does just what you are asking: String.indexOf(String).

See this link: http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#indexOf(java.lang.String)

So, then you could write this function:

public boolean isSubstring(String super, String sub) {
    return super.indexOf(sub) >= 0;
}
查看更多
登录 后发表回答