ในการพิมพ์อักขระทั่วไปของสองสตริงตามลำดับตัวอักษร รหัสจะเป็นดังนี้ −
ตัวอย่าง
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 is :
");
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 ตัวเป็นภาษาอังกฤษ) ความยาวของมันถูกเก็บไว้ในสองตัวแปรที่แตกต่างกันตามลำดับ
อาร์เรย์มีการวนซ้ำและที่ดัชนีที่แตกต่างกันระหว่าง ascii ของ 'a' และ ascii ของทุกอักขระ ascii ของอักขระ 'a' จะถูกลบออกจากค่า ascii ของอักขระทุกตัวและเพิ่มขึ้นทีละ 1 ซึ่งจะเติมเฉพาะค่าเหล่านั้นใน อาร์เรย์ที่เป็นเรื่องธรรมดา จำนวนอักขระขั้นต่ำจากอาร์เรย์ทั้งสองจะถูกคำนวณและพิมพ์บนคอนโซล ในฟังก์ชันหลัก สตริงทั้งสองจะถูกกำหนดและฟังก์ชันจะถูกเรียกโดยการส่งผ่านสตริงทั้งสองนี้เป็นพารามิเตอร์