第11次作业--字符串处理

题目1:编写一个应用程序,统计输入的一个字符串中相同字符的个数,并将统计结果输出。

/**  定义一个Statistics类,包含一个int[] counter(String str)方法,输入想统计的字符串,输出各字符的个数   */

Statistics类:

import java.util.Scanner;

public class Statistics {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入想统计的字符串:");
        String str = sc.nextLine();
        int[] b = counter(str);
        for(int i = 0; i < b.length; i++) {
            if(b[i] != 0) {
                System.out.print((char) (i + 'a')+":"+b[i]+",");
            }                
        }
    }

    public static int[] counter(String str) {
        int[] a = new int[26];
        int index=0;
        String str1 = str.replaceAll(" ", "");
        for(int i = 0; i < str1.length(); i++) {
            char c = str1.charAt(i);
            if(c>='a'&&c<='z') {
                index = c - 'a';
            }else if(c>='A'&& c<='Z'){
                index=c-'A';
            }
            a[index] = a[index] + 1;
        }
        return a;
    }
}

运行截图:

 

 

 

 

题目2:编写程序,输入一个字符串,判断该串中的字母能否组成一个回文串(回文串:一个字符串从前向后读取和从后向前读取都一样)。如:ab<c>c?ba

/**  创建一个Judge类,包含一个isJudge(String str)方法,键盘上输入一个字符串,输出此字符串是否为回文串。    */

Judge类:

import java.util.Scanner;

public class Judge {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner (System.in);
        System.out.println("请输入一个字符串");
        String str = sc.nextLine();
        System.out.println(isJudge(str));
    }
    public static boolean isJudge (String str){
        if(str.length()<=1){
            return true;
        }else if(str.charAt(0) != str.charAt(str.length()-1)){
            return false;
        }
        return isJudge(str.substring(1,str.length()-1));
    }
}

运行截图:

 

 

 

posted @ 2019-11-19 15:55  季英杰  阅读(228)  评论(0编辑  收藏  举报