统计从对键盘输入的一大段内容中所有不同符号的个数。
import java.util.Scanner;
public class Lab3_2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
int num[] = new int[100];
for(int i=0;i<=str.length()-1;i++){
char alp = str.charAt(i);
int t = alp-32;
num[t]++;
}
for(int k=0;k<=99;k++)
{
char s1 = ' ';
if(num[k] != 0)
{
s1 = (char) (' '+ k);
System.out.println(s1+" "+num[k]);
}
}
}
}
思路是将能显示出来的所有字符ASCII值确定,即从空格,到波浪号,ACSII值从32~126;对输入的每一个字符的ASCII减去32,方便数组计数,用一个int数组来计数字符的数目,初始数组全为0,而该数组的下标对应的就是字符的ASCII减去32。循环一遍字符串即可,时间复杂度为O(n),最后输出该数组中值不为0的。
import java.util.Scanner;
import javax.naming.InitialContext;
public class Lab3_2 {
Scanner sc = new Scanner(System.in);
static String s = new String("");
static int fun1(String s2,char t,int str1[],int number)
{
if(str1[s.indexOf(t)]!=0)
{
return 0;
}
if(s2.indexOf(t)==s2.lastIndexOf(t))
{
str1[s.indexOf(t)] = 1;
number++;
return number;
}
else {
String s1 = s2.substring(s2.indexOf(t),s2.lastIndexOf(t));
str1[s.lastIndexOf(t)] = 1;
number++;
return fun1(s1,t,str1,number);
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
s = sc.nextLine();
int str1[] = new int[100];
for(int i =0;i<s.length();i++)
{
int k =fun1(s,s.charAt(i),str1,0);
if(k!=0)
{
System.out.println(s.charAt(i)+" "+k);
}
}
}
}
第一种方法中不能解决有中文的问题,第二种方法可以,先声明一个int数组str,用来标记字符是否重复出现。使用了indexOf()和lastIntOf()函数,作用分别为返回某个字符或字符串首次出现的位置h和最后出现的位置t。若h==t,则说明该字符只有一个,若h!=t,说明不止一个,number++,将分割下标为[h~t)的字符串,递归继续重新,直至h==t,在此期间,每次都标记已经出现重复的t位置,令str[t] = 1。第一次写,新手上路,算法不好,最简便的应该是使用Map()类,但我还不会。。。。可以自行百度。。。。