Friday, 19 August 2016

Chapter 5 Exercise 51, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

*5.51 (Longest common prefix) Write a program that prompts the user to enter two strings and displays the largest common prefix of the two strings. Here are some sample runs:

Enter the first string: Welcome to C++
Enter the second string: Welcome to programming
The common prefix is Welcome to

Enter the first string: Atlanta
Enter the second string: Macon
Atlanta and Macon have no common prefix

import java.util.Scanner;
 
public class ProgrammingEx5_51 {
 
 public static void main(String[] args) {
  Scanner input = new Scanner(System.in);
  System.out.print("Enter the first string:");
  String s1 = input.nextLine();
  System.out.print("Enter the second string:");
  String s2 = input.nextLine();
 
  int l = s2.length();
  int p = 0;
 
  if (s1.length() < s2.length()) {
   l = s1.length();
  }
 
  for (int i = 0; i <= l; i++) {
   if (s1.charAt(i) != s2.charAt(i)) {
    break;
   }
   p++;
  }
 
  if (p == 0) {
   System.out.println(s1 + " and " + s2 + " have no common prefix");
   System.exit(0);
  }
 
  System.out.println("The common prefix is " + s1.substring(0, p));
 
 }
}

No comments :

Post a Comment