1 Importjava.util.ArrayList;2 ImportJava.util.HashSet;3 ImportJava.util.Iterator;4 Importjava.util.List;5 ImportJava.util.Set;6 7 /**8 * 9 * @authorTrfizengTen */ One Public classCountstr { A - //count occurrences of arbitrary strings - Public StaticList<string>countstr (String str) { the //A dictionary for storing the string to be detected -set<string> base =NewHashset<string>(); - //each character used to hold the input string -List<string> Totalstr =NewArraylist<string>(); + //the number of occurrences of each character to hold -List<string> coulist =NewArraylist<string>(); + //Convert a string to a character array A Char[] Tempchar =Str.tochararray (); at - //Initialize the dictionary and the characters to be counted - for(inti = 0; i < tempchar.length; i++) { -Base.add (tempchar[i]+ ""); -Totalstr.add (tempchar[i]+ ""); - } in -Iterator<string> it =base.iterator (); to //Initialize the number of occurrences of each character + while(It.hasnext ()) { -String string =(String) It.next (); theCoulist.add (String + ":" + 0); * } $ Panax Notoginseng //used to count the occurrences of each character - intc = 0; the //Start Traversal + for(inti = 0; I < totalstr.size (); i++) { AString TC =Totalstr.get (i); theiterator<string> ite =base.iterator (); + while(Ite.hasnext ()) { -String obj =Ite.next (); $ //determine if a character appears $ if(tc.equals (obj)) { - for(intj = 0; J < Coulist.size (); J + +) { -String CL =Coulist.get (j); the if(Cl.startswith (obj)) { - //take out the original number of occurrences +1Wuyic = Integer.parseint (Cl.substring (Cl.lastindexof (":") +1, Cl.length ())); theC++; - //number of occurrences from the new setting WuCoulist.set (J, obj + ":" +(c)); - } About } $ } - } - } - returncoulist; A } + the Public Static voidMain (string[] args) { -String teststr = "dfe:rrxc.:./haha yes:"; $List<string> cList =countstr (TESTSTR); the for(inti = 0; I < clist.size (); i++) { theSystem.out.print (Clist.get (i) + ""); the } the /* - * in Char []c=teststr.tochararray (); the map<string,integer> m=new hashmap<string, integer> (); the for (int i=0;i<c.length;i++) { About String cstr=string.valueof (C[i]); the if (Null!=m.get (CStr)) { the int Count=m.get (CSTR); the m.put (CStr, count+1); + }else{ - M.put (cstr,1); the } Bayi } the the */ - } -}
View Code
D:1/:1 r:2:: 3 c:1 ha: 2 f:1.: 2 X:1 there: 1 e:1
Statistics enter the number of characters in any string