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

后端 未结 16 1747
情歌与酒
情歌与酒 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:36
     String str="hello world";
            System.out.println(str.contains("world"));//true
            System.out.println(str.contains("world1"));//false
    
    • Javadoc
    0 讨论(0)
  • 2020-12-20 19:39

    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;
    }
    
    0 讨论(0)
  • 2020-12-20 19:39

    *In their any sub string will be count by the form of 1th place of string of substring *

    int isSubstring(string s1, string s2) {
        int M = s1.length();
        int N = s2.length();
    
        for (int i = 0; i <= N - M; i++) {
            int j;
            for (j = 0; j < M; j++)
                if (s2[i + j] != s1[j])
                    break;
    
            if (j == M)
                return i;
        }
    
        return -1;
    }
    
    
    int main() {
        string s1 = "kumar";
        string s2 = "abhimanyukumarroy";
        int res = isSubstring(s1, s2);
        if (res == -1)
            cout << "Not present";
        else
            cout << "Present at index " << res;
        return 0;
    }
    
    0 讨论(0)
  • 2020-12-20 19:40

    here is a general method that you can use

    public static boolean isSubstring(String s1, String s2) {
        if(s1.length() == s2.length()) 
            return s1.equals(s2);
        else if(s1.length() > s2.length())
            return s1.contains(s2);
        else
            return s2.contains(s1);
    
    }
    
    0 讨论(0)
提交回复
热议问题