5

I want to find the longest common prefix of two strings. Is there a way to loop my last couple of if statements so that I can end at the last characters that do not match each other?

System.out.println("Enter the first string: ");
String s = input.nextLine();

System.out.println("Enter the second string: ");
String s2 = input.nextLine();

//check if first characters are same
if (s.charAt(0) != s2.charAt(0)) {
  System.out.println(""+s+ " and "+s2+ " have no common prefix");
  System.exit(0);
    }

if (s.charAt(0) == s2.charAt(0))
  System.out.print(" "+s.charAt(0));

if (s.charAt(0) == s2.charAt(0))
  System.out.print(" "+s.charAt(1));

if (s.charAt(0) == s2.charAt(0))
  System.out.print(" "+s.charAt(2));  
  }
}

Example:

Enter first string: Welcome to c++

Enter second string: Welcome to java

The code should return Welcome to as the common prefix.

Anonymous
  • 11,748
  • 6
  • 35
  • 57
afrojuju_
  • 126
  • 1
  • 3
  • 12
  • 2
    Could you give some example what your code should do, because I'm not entirely sure that I get the idea? As far as I understand if you have `abc1` and `abc2` your code should say that the first 3 characters are matching and if it's `abcd1` and `abcd2` then the first four and so on... is that the idea? – Leron Mar 18 '14 at 23:36
  • test: Welcome to c++ Welcome to java return: Welcome to – afrojuju_ Mar 18 '14 at 23:50
  • @Dexters yes your answer works for me. is it possible to edit it without those packages?? and also can you explain how the code works? – afrojuju_ Mar 19 '14 at 00:17
  • @afrojuju_ I have added comments – Dexters Mar 19 '14 at 00:18
  • 1
    Possible duplicate of [Find longest common prefix?](https://stackoverflow.com/questions/8033655/find-longest-common-prefix) – JavaBeast Dec 05 '17 at 03:08

4 Answers4

3

Maybe something like:

int sLength = s.length(),
    s2Length = s2.length(),
    minLength = (sLength < s2Length) ? sLength : s2Length;

for (int i = 0; i < minLength; i++) {
    if (s.charAt(i) == s2.charAt(i)) {
        System.out.println(s.charAt(i));
    }
    else {
        break;
    }
}

But more details about your question would be great.

Edit: It depends what @afrojuju_ wants to do. That's not clear. Some more logic may be added to accomplish the desired behavior.

Edit 2: Added string length comparison as pointed out by @JavaBeast.

zrac
  • 153
  • 7
  • 2
    You'd probably want to `break;` when the `if` condition fails since there would be no need to continue looping once a non-matching character is found. – Paul Richter Mar 18 '14 at 23:44
  • 1
    I edited before seeing this comment. It makes sense. Somehow I didn't did the whole code because I wasn't sure what the question fully meant (as @afrojuju_ may search for "prefixes" inside string - it wouldn't be a prefix in its term but...) Anyway edited ;) – zrac Mar 18 '14 at 23:49
  • please check my question again. i added the test questions i wanted. Thanks @zrac – afrojuju_ Mar 18 '14 at 23:55
  • Answer is poor. Need to compare string length first to make sure in bounds. check out answer here: https://stackoverflow.com/questions/8033655/find-longest-common-prefix – JavaBeast Dec 05 '17 at 03:07
3

try this. I guess this is what you are trying to achieve. If this is correct I will add explanation later

import java.util.*;
import java.lang.*;
import java.io.*;

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        String s = "Hello Wo";
        String s2 = "Hello World";
        String small,large;
         if(s.length() > s2.length()) 
            {small = s2;large = s;}
          else
            {small = s;large = s2;}
        int index = 0;    
        for(char c: large.toCharArray())
        {
            if(index==small.length()) break;
            if(c != small.charAt(index)) break;
            index++;
        }
        if(index==0)
          System.out.println(""+s+ " and "+s2+ " have no common prefix");
        else
          System.out.println(large.substring(0,index));
    }
}

Edit:

  1. I find the larger of the strings and choose it to be the outer string to loop throught
  2. toCharArray() converts the string into characters so you can loop through each characters in the string using Java's foreach (For more click[1])
  3. Inside the loop you should exit on two conditions
    • End of the string (I use length to find if I reach end of smaller string)
    • no more matching characters between two strings
  4. you increment the index until you break out in one of the above conditions
  5. By the time you break out of the for loop, index will contain the last index where both string are continuously equal.
  6. If index = 0. just say no matches else print characters from 0 until index
Community
  • 1
  • 1
Dexters
  • 2,419
  • 6
  • 37
  • 57
0
    public static String LcpFinder (String s1 , String s2){

    if (s1 == null || s2 == null){
        throw new IllegalArgumentException();
    }

    int minLength = 0;

    if (s1.length() < s2.length()){
        minLength = s1.length();
    }
    else{
        minLength = s2.length();
    }

    for (int i = 0 ; i < minLength ; i++){

        if(s1.charAt(i) == s2.charAt(i)){
            continue;
        }
        else{
            return s1.substring(0,i);
        }           
    }
    return s1.substring(0,minLength); 
}
Gökhan Akduğan
  • 533
  • 1
  • 8
  • 17
0

Try with this code block:

    str1 = input().lower()
    str2 = input().lower()
    
    for i in range(min(len(str1),len(str2))):
        if str1[i] != str2[i]:
            break
    
    if i == 0:
        print(-2)
    else:
        print(str1[:i])
Md. Nashir Uddin
  • 730
  • 7
  • 20
  • 1
    While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. – Yunnosch Dec 25 '22 at 22:16
  • However, this does not look like java code and seems odd as a solution to a java-tagged question. – Yunnosch Dec 25 '22 at 22:17