Java程式碼,按字母順序列印兩個字串的公共字元
在本文中,我們將學習如何使用Java按字母順序列印兩個字串的公共字元。該程式使用陣列來計算每個字母在兩個字串中出現的頻率,然後比較這些計數以識別公共字元。
問題陳述
編寫一個Java程式,按字母順序列印兩個字串的公共字元:
輸入
my_str_1 = "itsasample"
my_str_2 = "thisisasample"
輸出
The common characters between the two strings in alphabetical order is :
aaeilmpsst
按字母順序列印兩個字串的公共字元的步驟
以下是按字母順序列印兩個字串的公共字元的步驟:
- 首先,我們將從java.io和java.util包匯入所有必要的類。
- 之後,我們將定義一個包含common_chars方法的類**Demo**。
- 建立兩個大小為26的陣列,用於跟蹤每個字串的字母頻率。
- 使用for迴圈遍歷兩個字串,用字母計數填充陣列。
- 比較陣列並根據它們的頻率列印公共字元。
- 在主方法中,使用兩個預定義的字串呼叫**common_chars**。
列印兩個字串的公共字元的Java程式碼
以下是按字母順序列印兩個字串的公共字元的Java程式碼,程式碼如下:
import java.io.*;
import java.util.*;
public class Demo {
static void common_chars(String str_1, String str_2) {
int[] array_1 = new int[26];
int[] array_2 = new int[26];
int str_len_1 = str_1.length();
int str_len_2 = str_2.length();
for (int i = 0; i < str_len_1; i++)
array_1[str_1.charAt(i) - 'a'] += 1;
for (int i = 0; i < str_len_2; i++)
array_2[str_2.charAt(i) - 'a'] += 1;
for (int i = 0; i < 26; i++) {
if (array_1[i] != 0 && array_2[i] != 0) {
for (int j = 0; j < Math.min(array_1[i], array_2[i]); j++)
System.out.print(((char)(i + 'a')));
}
}
}
public static void main(String[] args) throws IOException {
String my_str_1 = "itsasample";
String my_str_2 = "thisisasample";
System.out.println("The common characters between the two strings in alphabetical order are:");
common_chars(my_str_1, my_str_2);
}
}
輸出
The common characters between the two strings in alphabetical order is : aaeilmpsst
程式碼解釋
名為Demo的類包含一個名為**‘common_chars’**的函式,該函式聲明瞭兩個大小為**26**(表示英語中的26個字母)的整數陣列。它們的長度儲存在兩個不同的變數中。
遍歷陣列,在'a'的ASCII碼與每個字元的ASCII碼之差的索引處。從每個字元的ASCII值中減去字元'a'的ASCII值,然後加1。這將只填充陣列中那些公共的值。計算並列印兩個陣列中的最小字元數。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP