1

I'm trying to find a part of str1 inside str2 (two strings). Currently I have a working program however it's not exactly working correctly or using the correct logic in my opinion.

public static void main(String[] params) {
    String str1 = "blis";
    String str2 = "grisdisbliszis";
    //String str2 = "adasdsfgsdfdcx";
    System.out.println(isCommonSubstring(str1, str2));
}

public static boolean isCommonSubstring(String str1, String str2) {

    char char1, char2;
    boolean match = true;
    String check = "";

    for(int i = 0; i < str1.length(); i++) {
        char1 = str1.charAt(i);
        for(int j = 0; j < str2.length(); j++) {
            char2 = str2.charAt(j);
            if(char1 == char2) {
                check += char1;
                System.out.println("Matched!: "+str1.charAt(i)+"[Char "+i+"] <==> " // DEBUG
                    +str2.charAt(j)+"[Char "+j+"]");                                // DEBUG
                break; // Break because we've found our first match and we need to check others
            }
        }
    }
        System.out.println(check+" || "+str1);
        if(check.equals(str1)) match = true;
            else match = false;

    return match;
}

This may work but if I turn these two strings around it no longer works.

How can I improve the logic of finding a match? I tried to possibly use substring() somehow however I'm not sure how to fit it inside.

The solution I'm thinking of is possibly making if statements to compare lengths and make str2 the longer length so it's always longer and does not cause errors. But is this a decent solution?

I can only use length, substring and charAt.

26
  • Is there some reason you're not using either the built-in String function or a utility like StringUtils? Commented Oct 14, 2015 at 21:01
  • 2
    You should be clear if you cannot use the existing Java String API or not. Is this homework? Commented Oct 14, 2015 at 21:01
  • 1
    Forgot to mention I cannot use anything other than length, substring and charAt. Sorry. Commented Oct 14, 2015 at 21:04
  • 1
    Are you actually trying to find a common substring? If so, the name isSubstring is misleading, because it leads the readers to think your method is checking if str1 is a substring of str2. Commented Oct 14, 2015 at 21:04
  • 1
    @Xylus don't give up one your code you are close... just check the comments Commented Oct 14, 2015 at 21:41

3 Answers 3

2

The algorithm here would be the following :

  1. Use a main loop that will stop either when the word is found, or when we've reached his length minus the length of the second string. (For example : If str1 has a length of 6 and str2 a length of 4, we know str2 does not begin at index 3 for example).

  2. Use a second loop to check if the indexes of str2 fit somehow in str1. We check each index, one after the other inside the inner. If one of them doesn't correspond to the looped indexes of the main loop, we break from the inner loop and add one to the index of the main loop.

  3. If the inner loop finished succesfully, we know that the word is found.


Here is a short solution possible using only charAt() and lenght():

    static boolean isCommonSubstring (String one, String two) {
        if (one.length() < two.length()){
            String tmp = one;
            one = two;
            two = tmp;
        }
        MAIN :
        for (int i = 0 ; i <= one.length()-two.length() ; i++){
            for (int j = 0 ; j < two.length() ; j++){
                if ((one.charAt(i+j) != two.charAt(j))) continue MAIN;
            }
            return true;
        }
        return false;
    }
Sign up to request clarification or add additional context in comments.

9 Comments

Maybe we help more if we do not provide own code, but help figuring out how to do it themself...., i will not down vote since you are correct
You're right Petter. That is the reason why I added the explanation.
Provide some notion to xylus what he need to do to make his code work, and you will get my upvote (specially since he does not wan't to be forced to pass first the longest and then the shortes... hence you have same result as xylus if you invert one and two
Whats does your metod return if String one = "blis" and String two = "grisdisbliszis"? see comments under question to understand..
Just invert the strings.. You can not have a string containing a greater string...
|
1

String.contains() is what you are looking for.

Simple tutorial

Unless you have requirements not to use builtin functions, dont reinvent the wheel.

Example from tutorial link above:

String str1 = "tutorials point", str2 = "http://";

   CharSequence cs1 = "int";

   // string contains the specified sequence of char values
   boolean retval = str1.contains(cs1);
   System.out.println("Method returns : " + retval);

   // string does not contain the specified sequence of char value
   retval = str2.contains("_");   
   System.out.println("Methods returns: " + retval);
   }

If you want case insensitive:

str1.toLowerCase.contains(str2.toLowerCase());

EDIT turns out OP cannot use builtin functions. Will leave the answer here just in case any one else comes here who doesn't want to reinvent the wheel :)

2 Comments

I removed my upvote, seems like OP cannot use built in functions, so your solution (however correct) will not be helpful.
@Ceelos. Yeah thats understandable. But someone else downvoted and just want to know if I made a mistake.
0

I can only use length, substring and charAt

Since you can only use those methods. This is what you can do:

//Self-defined method to check whether sub exist in str
public static boolean contains(String str, String sub){
    if(sub.length() > str.length())
        return false;    

    for(int x=0; x<= str.length() - sub.length(); x++)
        if(str.substring(x, sub.length()+x).equals(sub))                
            return true;                            
    return false;
} 

EXPLANATION:

The loop will the check whether sub exist in str in the following approach:

apple (Compare "app" with "ple"  ==> does not match);
^^^    
apple (Compare "ppl" with "ple"  ==> does not match);
 ^^^    
apple (Compare "ple" with "ple"  ==> match, return true);
  ^^^

TESTING:

String a = "apple";
String b = "ple";   
System.out.println(a + " contains " + b + ": " + contains(a, b));

OUTPUT:

apple contains ple: true

3 Comments

Note xylus does not like to first pass the longest and then the shortest... this is his problem... check comments...
@PetterFriberg If that is the case, he can simply swap the arguments "str" and "sub". Actually it is not even a problem at all. By improvising on my codes a little, str1 can be longer than str2 and vice versa.
Well if you read the comments on the question you will found out what the problem was.. I will move on have fun...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.