第一题:
import java.util.Scanner;
public class Test03 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("请输入要统计的字符串");
String str=sc.nextLine();
int c=count(str);
System.out.println("该字符串里nba出现的个数为:"+c);
}
public static int count(String str) {
// TODO Auto-generated method stub
int c=0;
while(true){
int b=str.indexOf("nba");
if(b>=0){
str=str.substring(b+"nba".length());
c++;
}else{
break;
}
}
return c;
}
}
第二题:
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.TreeMap;
public class Test04 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("请输入要被打印的字符串:");
String str=sc.nextLine();
print(str);
}
public static void print(String str) {
// TODO Auto-generated method stub
TreeMap<Character, Integer> tm=new TreeMap<>();
for (int i = 0; i < str.length(); i++) {
char ch=str.charAt(i);
tm.put(ch, !tm.containsKey(ch) ? 1 : tm.get(ch)+1);
}
for (Entry<Character, Integer> en: tm.entrySet()) {
System.out.print(en.getKey()+"("+en.getValue()+")");
}
}
} |