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

一、题目1

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

二、源代码

/**使用HashMap类实现Map接口,用Map集合里的方法来进行操作*/
package com;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
public class Test {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc=new Scanner(System.in);
        System.out.println("请输入字符串:");
        String str=sc.nextLine();
        //声明HashMap对象
        HashMap<Character, Integer> hashMap=new HashMap<Character, Integer>();
        for (int i = 0; i < str.length(); i++) {
            char c=str.charAt(i);
            //hashMap中没有此元素,则添加至map集合中
            if(!hashMap.containsKey(c)){ //判断Map集合中是否包含'c'
                hashMap.put(c,1);
            }else {
                int count=hashMap.get(c);
                count++;//Map集合中存在此元素,则将值加1
                hashMap.put(c, count);//添加数据
            }
        }
        Set<Map.Entry<Character, Integer>> entries=hashMap.entrySet();
        for(Map.Entry<Character, Integer> entry:entries){
            System.out.println(entry.getKey()+"("+entry.getValue()+")");
        }
    }
}

三、运行结果

 

一、题目2

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

二、源代码

/**输入一串字符,创建StringBuffer对象,用reverse()方法逆置与原字符串比较,用正则表达式去除非字母字符
 */
package com;
import java.util.Scanner;
public class Test2 {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc=new Scanner(System.in);
        System.out.println("请输入一串字符:");
        String str=sc.nextLine();
        //正则表达式去除标点符号和空格
        String str1 = str.replaceAll("[\p{Punct}\p{Space}]+","");
        StringBuffer str2=new StringBuffer(str1);
        if(str1.equals(str2.reverse().toString())){
            System.out.println(str1+"是回文");
        }else {
            System.out.println(str1+"不是回文");
        }
    }
}

三、运行结果

 

 

原文地址:https://www.cnblogs.com/jingxueyan/p/11891957.html