문자열 클래스를 사용하여 문자열을 나타낼 수 있습니다. , 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