7

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!

Luixv
  • 8,590
  • 21
  • 84
  • 121
  • 3
    `str.indexOf(substr) != -1` is the answer. – biziclop Jan 26 '11 at 12:40
  • Well, so many right answers together in that less time. Thanks a lot to you all. You saved my a lot of time. I am using java 1.5 and I was looking at the documentation of java 1.4.2 therefore I didn't realize that there exists the method "contains". The subindexing approach is also OK. +1 to you all. – Luixv Jan 26 '11 at 12:51
  • @biziclop in case you missed it, you need to post answers in the Answers section below. – dogbane Jan 26 '11 at 12:53
  • @dogbane I can but I don't have to. :) – biziclop Jan 26 '11 at 13:22

16 Answers16

24

There is a contains() method! It was introduced in Java 1.5. If you are using an earlier version, then it's easy to replace it with this:

str.indexOf(substr) != -1
Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
5
 String str="hello world";
        System.out.println(str.contains("world"));//true
        System.out.println(str.contains("world1"));//false
jmj
  • 237,923
  • 42
  • 401
  • 438
3
  String s = "AJAYkumarReddy";
    String sub = "kumar";
    int count = 0;
    for (int i = 0; i < s.length(); i++) {
        if (s.charAt(i) == sub.charAt(count)) {
            count++;
        } else {
            count = 0;
        }
        if (count == sub.length()) {
            System.out.println("Sub String");
            return;
        }

    }
ajay
  • 477
  • 6
  • 14
2

use indexOf it will return -1 if no match (contains was added in 1.5, maybe you are using older jdk?) see "contains(CharSequence s)" method in String class in JDK 1.4.2 for details

Community
  • 1
  • 1
Joelio
  • 4,621
  • 6
  • 44
  • 80
1
    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;
}
1

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);

}
Quan
  • 19
  • 2
1
if (str.indexOf(substr) >= 0) {
    // do something
}
Papuass
  • 327
  • 1
  • 10
1

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;
}
OEP
  • 448
  • 2
  • 11
1

String.indexOf(substr) complexity is O(n2).. Luixv asked a cheaper solution.. But as far as , I know there is no better algorithm than current one.

Gursel Koca
  • 20,940
  • 2
  • 24
  • 34
0
public static boolean isSubstring(String s1, String s2){
    if(s1.length()<s2.length()) return false;
    if(s1.length()==s2.length()) return s1.equals(s2);
    for(int i=0;i<=s1.length()-s2.length();i++){
        if(s1.charAt(i)==s2.charAt(0)){
            int matchLength=1;
            for(int j=1;j<s2.length();j++){
                if(s1.charAt(i+j)!=s2.charAt(j)){
                    break;
                }
                matchLength++;
            }
            if(matchLength==s2.length()) return true;
        }
    }
    return false;
}

This checks if s2 is a substring of s1.

0

You can use .substring(int beginIndex,int lastIndex) to check this program. Sample code goes as below:-

public class Test {

    public static void main(final String[] args) {
        System.out.println("Enter the first String");
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        try {
            String s1 = br.readLine();
            System.out.println("Enter the second String");
            String s2 = br.readLine();

            boolean result = isSubStr(s1, s2);
            if (result == true)
                System.out.println("The second String is substring of the first String");
            else
                System.out.println("The second String is not a substring of the first String");

        } catch (IOException e) {
            System.out.println("Exception Caught: " + e);
        }

    }

    public static boolean isSubStr(String st1, String s2) {

        boolean result = false;

        String tem_str = "";
        int len1 = st1.length();
        int i = 0;
        int j;

        while (i < len1) {
            j = i+1;
            while (j <=len1) {
                tem_str = st1.substring(i, j);
                if (tem_str.equalsIgnoreCase(s2)) {
                    result = true;
                    break;
                }
               j++;
            }

            i++;
        }
        return result;
    }
}
Fredrik Widerberg
  • 3,068
  • 10
  • 30
  • 42
0

Go through this method. visit for tricky code

public static boolean isSubString(String s, String sub) {
    int count = 0;
    for (int i = 0; i < s.length(); i++) {
        if (s.charAt(i) == sub.charAt(count)) {
            count++;
        } else {
            i-=count;
            count = 0;
        }
        if (count == sub.length()) {
            return true;
        }

    }
    return false;
}
  • Welcome to Stack Overflow! Please do not add links that are necessary to add to the explanation or else they would be treated by the community as SPAM and your answer might be removed. – Aditya Oct 31 '18 at 12:36
  • However the solution you suggested is relatively inefficient and very effective. You should look at KMP Algorithm which is much more efficient and used almost everywhere. – Aditya Oct 31 '18 at 12:40
0

Consider the following code:

If substring is present then it returns the start index of substring in a given string

Else returns -1

public static int isSubstring(String str, String pattern)
{
    int str_length = str.length();
    int pattern_length = pattern.length();

    for (int i = 0; i <= str_length - pattern_length; i++)
    {
        int j;

        for (j = 0; j < pattern_length; j++)
            if (str.charAt(i + j) != pattern.charAt(j))
                break;

        if (j == pattern_length)
            return i;
    }
    return -1;
}
Community
  • 1
  • 1
Pratik Patil
  • 3,662
  • 3
  • 31
  • 31
0
    String str1 = "Java8 makes Java more powerful";
    String str2 = "Java";
    char c;
    char d;
    int count=0;
    boolean match = true;
    for (int i = 0; i < str1.length(); i++) {
        c = str1.charAt(i);
        for (int j = 0; j < str2.length(); j++) {
            d = str2.charAt(j);
            if (c == d) {
                match = true;
                count++;
                if(count== str2.length()){
                    i = str1.length();
                    break;
                }
                i++;
                c = str1.charAt(i);
            } else {
                match = false;
            }   
        }
    }

    if(match == true){
        System.out.println("SubString ");
    }
Kuladip
  • 154
  • 1
  • 10
0
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;       
        }
    }
}
ChrisMM
  • 8,448
  • 13
  • 29
  • 48
sonia
  • 1
  • 2
0

*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;
}
damjad
  • 1,252
  • 1
  • 15
  • 24
ABHI ROY
  • 1
  • 2