Write a program that has a method commonPre (String str1, String str2) that
returns the common prefix of two strings. For example, the common prefix of “distance” and
“disinfection” is “dis”. If the two strings have no common prefix, the method displays “No
common prefix”. The user should be prompted to enter two strings in JOptionPane and
display their common prefix, if any. Use JOptionPane for all inputs and outputs.
import javax.swing.JOptionPane;
public class App {
/**
* The start point of the program
*
* @param args
*
*/
public static void main(String[] args) {
String str1 = JOptionPane.showInputDialog("Enter the string 1: ");
String str2 = JOptionPane.showInputDialog("Enter the string 2: ");
JOptionPane.showMessageDialog(null, commonPre(str1, str2));
}
private static String commonPre(String str1, String str2) {
int minLenght = str1.length();
if (minLenght > str2.length()) {
minLenght = str2.length();
}
String commonPrefix = "";
for (int i = 0; i < minLenght; i++) {
if (str1.charAt(i) == str2.charAt(i)) {
commonPrefix += str1.charAt(i);
} else {
if (commonPrefix.length() > 0) {
return commonPrefix;
} else {
break;
}
}
}
if (commonPrefix.length() > 0) {
return commonPrefix;
}
return "No common prefix";
}
}
Comments
Leave a comment