A สตริง คลาสสามารถใช้เพื่อแสดง สตริงอักขระ , ตัวอักษรสตริงทั้งหมดในโปรแกรม Java ถูกนำมาใช้เป็นตัวอย่างของ String ระดับ. สตริงเป็นค่าคงที่และค่า ไม่สามารถเปลี่ยนแปลงได้ (เปลี่ยนไม่ได้) เมื่อสร้างแล้ว
ในโปรแกรมด้านล่าง เราสามารถพิมพ์อักขระสูงสุดที่เกิดขึ้น ของสตริงที่กำหนด
ตัวอย่าง
public class MaxOccuredCharacterTest {
public static void main(String[] args) {
String str1 = maxOccuredChar("tutorialspoint");
System.out.println(str1);
String str2 = maxOccuredChar("AABBAABBCCAABBAA");
System.out.println(str2);
String str3 = maxOccuredChar("111222333444333222111");
System.out.println(str3);
}
public static String maxOccuredChar(String str) {
char[] array = str.toCharArray();
int maxCount = 1;
char maxChar = array[0];
for(int i=0, j=0; i < str.length()-1; i=j) {
int count = 1;
while(++j < str.length() && array[i] == array[j]) {
count++;
}
if (count > maxCount) {
maxCount = count;
maxChar = array[i];
}
}
return (maxChar + " = " + maxCount);
}
} ผลลัพธ์
t = 1 A = 2 1 = 3