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.
The longest common prefix for an array of strings is the common prefix between 2 most dissimilar strings. For example, in the given array {“apple”, “ape”, “zebra”}, there is no common prefix because the 2 most dissimilar strings of the array “ape” and “zebra” do not share any starting characters.
To solve this, we will take the first string as curr, now take each string from the array and read them character by character, and check the characters between curr, and the taken string one by one. If they are same go for next character, otherwise break the loop, and update the curr as the substring that has matched.
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));
}
}
toCharArray()
converts the string into characters so you can loop through each characters in the string using Java's foreach (For more click[1])index
will contain the last index where both string are continuously equal.index
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With