Skip to main content
Tweeted twitter.com/#!/StackCodeReview/status/201088165510000640
improved formatting
Link
palacsint
  • 30.4k
  • 9
  • 82
  • 157

Is there a way to improve my method to find Find two equal substrings in a string?

Source Link

Is there a way to improve my method to find two equal substrings in a string?

I have various strings that contain codes, e.g. like this:

"file = new JarFile(new File()" + "\nSystem.out.println(file"

but also

"args"

Now I want to find the substring that is in the beginning and in the end of the string. E.g. in the first case the result would be file. In the second example the result has to be args

I now wrote the following method:

public static String findWord(String text) {
        String result = null;
        boolean found = false;
        for (int i = 0; i < text.length(); i++) {
            for (int j = 0; j < text.length(); j++) {
                String first = text.substring(0, i*j);
                String last = text.substring(text.length() - i*j, text.length());
                if (first.equals(last) && first.length() > 0) {
                    result = first;
                    found = true;
                    break;
                }
            }
            if (found) {
                break;
            }
        }
        return result;
    }

This seems to work for the test cases I tested, but I'm not sure if it works for all cases. Additionally, I'm not sure if there isn't a simpler solution. I need two loops and ugly break statements. So how could I improve that?