定義一個方法,求出字串中有多少種字符,以及每個字符的個數
static void printCharInfo(String str) 例如有字串 str="apple is a apple.";
方式一:
public class String05 {
public static void main(String[] args) {
String str="apple is a apple.";
printCharInfo(str);
}
static void printCharInfo(String str){
char[] a=new char[50];
int[] b=new int[50];
char[] ch=str.toCharArray(); //將字串轉換為字符陣列
int index=0;
for(int i=0;i<str.length();i++){
if(i!=0)
for(int j=0;j<index;j++){
if(a[j]==ch[i]){
b[j]++;
break;
}else if(j==index-1){
a[index++]=ch[i];
b[index-1]=1;
break;
}
}
else{
a[index++]=ch[i];
b[index-1]=1;
}
}
System.out.println("字串中有"+index+"種字符");
System.out.println("每個字符的個數為:");
for(int i=0;i<index;i++){
System.out.println(a[i]+" :"+b[i]);
}
}
}
方式二:
public class String06 {
public static void printCharInfo(String str) {
int index=0;
while(str.length()>0) {
int n=str.length();
String a=str.charAt(0)+"";
str=str.replace(a,"");
System.out.println(a+":"+(n-str.length()));
index++;
}
System.out.println("字串的種類為:"+index+"種");
}
public static void main(String[] args) {
String s="apple is a apple.";
String06.printCharInfo(s);
}
}
運行結果:

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/413289.html
標籤:其他
