首页 > 代码库 > 统计字符 比如aaabbcca----3a2b1c1a

统计字符 比如aaabbcca----3a2b1c1a

package Demo;

import java.util.Scanner;

/**
 * Created by chengpeng on 16/11/3.
 */

/*
idea command+alt+o remove invalid import
 */
public class StringStatistics {


    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str="";
        while(sc.hasNext()){
            str = sc.nextLine();//aaabbcca----3a2b1c1a
            System.out.println(statistics(str));

        }
        sc.close();

    }


    private static String statistics(String str) {
        if(str==null) return null;
        int begin=0;
        int end=str.length()-1;
        String reStr ="";
        int count =1;
        while(begin<=end){
            if ((begin<end-1)&&(str.charAt(begin)==str.charAt(begin+1))){
                begin++;
                count++;
            }else {
                reStr+=count+String.valueOf(str.charAt(begin));
                begin++;
                count=1;
            }

        }
        return reStr;
    }
}

 

统计字符 比如aaabbcca----3a2b1c1a