去除一个字符串中出现的重复字符,并计算出出现最多次的字符的出现次数

时间:2023-01-09 11:22:11

/*

 * 典例子,去除一个字符串中出的重字符,并算出出最多次的字符的出次数

 * 主要是使用了Map个数据对应一个键值标识)的特性,非常巧妙的解决了问题

 **/

/*

 *本程序源出自csdn jFresH_MaN(The answer is ......),是我在论坛上抄下来的,在此向他表示感

 * */

import java.util.*;

public class Test {

              public static void main(String[] args) {

                            StringBuffer strBuf=new StringBuffer("a,b,c,d,e,f,a,a,d,c,c");

                            StringTokenizer st=new StringTokenizer(strBuf.toString(),",");

                            /*

                             * StringTokenizer在此的使用也很好,所要理的字符串有","一特定的分隔符

                             * 正好发挥StringTokenizer的效用

                             * */

                            Map set=new HashMap();

                            while(st.hasMoreTokens()) {

                                          String temp=st.nextToken();

                                          Object o=set.get(temp);

                                          if(o==null)

                                       set.put(temp,new Integer(1));

                                          else

                                       set.put(temp,new Integer(((Integer)o).intValue()+1));

                            }

                            Iterator i=set.keySet().iterator();

                            while(i.hasNext()) {

                                          System.out.print((String)i.next()+" ");

                            }

                            System.out.println();

                            Integer integer=(Integer)Collections.max(set.values());

                            /*Collections.max(set.values())方法用得妙,省去了不少自己行比时间

                             * */

                            System.out.println(integer.intValue());       

              }

}

把字符串倒转输出:(像逗号,空格符也要在输出中体现出来)

import java.util.StringTokenizer;

public class Test{

    public static final String SEPARATORS = " ,/t:'';?!";

    public static String reverse(String input){
   
        StringTokenizer st = new StringTokenizer(input, SEPARATORS, true);
        StringBuffer words = new StringBuffer("");
        while (st.hasMoreTokens()) {
            words.insert( 0, st.nextToken() );
        }   
        return words.toString();
    }       
   
    public void testReverse(){
       
        String[] sentences = new String[]{
            "Hello, world!",
            "I am a student",
            "Am I a student? yes, or no",
            "Am I a student ? yes , or no",
            "Zhuang says:'It's just a coding game.'"
            };
           
        for (int i = 0; i < sentences.length; i++)
            System.out.println("Sentence[" + i + "]=[" + sentences[i]+"], " +
                "After reversed: [" + Test.reverse(sentences[i])+"]");
       
    }
   
    public static void main(String[] args){
        new Test().testReverse();
    }
   
       
}