Java黑皮书课后题第5章:*5.51(最长的共同前缀)编写一个程序,提示用户输入两个字符串,显示两个字符串最长的共同前缀
生活随笔
收集整理的這篇文章主要介紹了
Java黑皮书课后题第5章:*5.51(最长的共同前缀)编写一个程序,提示用户输入两个字符串,显示两个字符串最长的共同前缀
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
5.51(最長的共同前綴)編寫一個程序,提示用戶輸入兩個字符串,顯示兩個字符串最長的共同前綴
- 題目
- 題目概述
- 運行示例
- 破題
- 代碼
題目
題目概述
5.51(最長的共同前綴)編寫一個程序,提示用戶輸入兩個字符串,顯示兩個字符串最長的共同前綴
運行示例
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 Test5_51 {public static void main(String[] args) {// 1. 獲取用戶輸入的兩個字符串(假設一個為a,一個為b)Scanner input = new Scanner(System.in);System.out.print("Enter the first string: ");String str_1 = input.nextLine();System.out.print("Enter the second string: ");String str_2 = input.nextLine();// 獲取str_1和str_2的長度int length_1 = str_1.length();int length_2 = str_2.length();int length = Math.max(length_1, length_2);// 2. 對a和b同時用substring()方法進行切割,并進行比較,直到不匹配為止String cut_str1 = "", cut_str2="", temp="";int count = 0;for (int i = 1 ; i <= length ; i++){cut_str1 = str_1.substring(0,i);cut_str2 = str_2.substring(0,i);if (cut_str1.equals(cut_str2)){temp = cut_str1;++count;} else {break;}}//3. 輸出不匹配之前(進行比較)的字符串if (count != 0){System.out.print("The common prefix is " + temp);}elseSystem.out.print(str_1 + " and " + str_2 + " have no common prefix");} }總結
以上是生活随笔為你收集整理的Java黑皮书课后题第5章:*5.51(最长的共同前缀)编写一个程序,提示用户输入两个字符串,显示两个字符串最长的共同前缀的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java黑皮书课后题第5章:*5.50(
- 下一篇: Java黑皮书课后题第6章:6.1(数学