日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

Java黑皮书课后题第5章:*5.51(最长的共同前缀)编写一个程序,提示用户输入两个字符串,显示两个字符串最长的共同前缀

發布時間:2024/7/23 java 32 豆豆

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

破題

  • 獲取用戶輸入的兩個字符串(假設一個為a,一個為b)
  • 對a和b同時用substring()方法進行切割(從下標0到下標1、從下標0到下標2……),切割后得到的子字符串進行比較,直到不匹配為止
  • 輸出不匹配之前(進行比較)的字符串
  • 代碼

    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(最长的共同前缀)编写一个程序,提示用户输入两个字符串,显示两个字符串最长的共同前缀的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。