在String中查找重复字符并使用Java计算出现次数

如何查找字符串中字符的出现次数?

例如:快速的棕色狐狸跳过懒狗

下面是一些示例输出,

'a' = 1 'o' = 4 'space' = 8 '.' = 1 

如果String s是您要处理的字符串,则可以使用以下命令。

 Map map = new HashMap(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (map.containsKey(c)) { int cnt = map.get(c); map.put(c, ++cnt); } else { map.put(c, 1); } } 

请注意,它将计算所有字符,而不仅仅是字母。

  void Findrepeter(){ String s="mmababctamantlslmag"; int distinct = 0 ; for (int i = 0; i < s.length(); i++) { for (int j = 0; j < s.length(); j++) { if(s.charAt(i)==s.charAt(j)) { distinct++; } } System.out.println(s.charAt(i)+"--"+distinct); String d=String.valueOf(s.charAt(i)).trim(); s=s.replaceAll(d,""); distinct = 0; } } 
 import java.io.*; public class CountChar { public static void main(String[] args) throws IOException { String ch; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter the Statement:"); ch=br.readLine(); int count=0,len=0; do { try { char name[]=ch.toCharArray(); len=name.length; count=0; for(int j=0;j=65&&name[0]<=91)||(name[0]>=97&&name[0]<=123))) count++; } if(count!=0) System.out.println(name[0]+" "+count+" Times"); ch=ch.replace(""+name[0],""); } catch(Exception ex){} } while(len!=1); } } 

产量

 Enter the Statement:asdf23123sfsdf a 1 Times s 3 Times d 2 Times f 3 Times 

更好的方法是创建一个Map来存储您的计数。 这将是Map

您需要遍历字符串的每个字符,并检查它是否是字母表。 您可以使用Character#isAlphabetic方法。 如果是alphabet ,请在Map增加其计数。 如果角色尚未在Map则添加计数为1

注意 : – Character.isAlphabetic方法是Java 7新方法。 如果您使用的是旧版本,则应使用Character#isLetter

  String str = "asdfasdfafk asd234asda"; Map charMap = new HashMap(); char[] arr = str.toCharArray(); for (char value: arr) { if (Character.isAlphabetic(value)) { if (charMap.containsKey(value)) { charMap.put(value, charMap.get(value) + 1); } else { charMap.put(value, 1); } } } System.out.println(charMap); 

输出 : –

 {f=3, d=4, s=4, a=6, k=1} 

Java 8方式:

 "The quick brown fox jumped over the lazy dog." .chars() .mapToObj(i -> (char) i) .collect(Collectors.groupingBy(Object::toString, Collectors.counting())); 

这是不使用任何Collection和n的复杂度顺序的实现。虽然接受的解决方案足够好并且不使用Collection但是看起来,它没有处理特殊字符。

 import java.util.Arrays; public class DuplicateCharactersInString { public static void main(String[] args) { String string = "check duplicate charcters in string"; string = string.toLowerCase(); char[] charAr = string.toCharArray(); Arrays.sort(charAr); for (int i = 1; i < charAr.length;) { int count = recursiveMethod(charAr, i, 1); if (count > 1) { System.out.println("'" + charAr[i] + "' comes " + count + " times"); i = i + count; } else i++; } } public static int recursiveMethod(char[] charAr, int i, int count) { if (ifEquals(charAr[i - 1], charAr[i])) { count = count + recursiveMethod(charAr, ++i, count); } return count; } public static boolean ifEquals(char a, char b) { return a == b; } } 

输出:

 ' ' comes 4 times 'a' comes 2 times 'c' comes 5 times 'e' comes 3 times 'h' comes 2 times 'i' comes 3 times 'n' comes 2 times 'r' comes 3 times 's' comes 2 times 't' comes 3 times 

使用google guava Multiset

 Multiset wordsMultiset = HashMultiset.create(); wordsMultiset.addAll(words); for(Multiset.Entry entry:wordsMultiset.entrySet()){ System.out.println(entry.getElement()+" - "+entry.getCount()); } 
 public static void main(String args[]) { char Char; int count; String a = "Hi my name is Rahul"; a = a.toLowerCase(); for (Char = 'a'; Char <= 'z'; Char++) { count = 0; for (int i = 0; i < a.length(); i++) { if (a.charAt(i) == Char) { count++; } } System.out.println("Number of occurences of " + Char + " is " + count); } } 
 public static void main(String[] args) { String name="AnuvratAnuvra"; char[] arr = name.toCharArray(); HashMap map = new HashMap(); for(char val:arr){ map.put(val,map.containsKey(val)?map.get(val)+1:1); } for (Entry entry : map.entrySet()) { if(entry.getValue()>1){ Character key = entry.getKey(); Object value = entry.getValue(); System.out.println(key + ":"+value); } } } 

A级{

 public static void getDuplicates(String S) { int count = 0; String t = ""; for (int i = 0; i < S.length() - 1; i++) { for (int j = i + 1; j < S.length(); j++) { if (S.charAt(i) == S.charAt(j) && !t.contains(S.charAt(j) + "")) { t = t + S.charAt(i); } } } System.out.println(t); } 

}

B级公共B级{

 public static void main(String[] args){ A.getDuplicates("mymgsgkkabcdyy"); } 

}

使用Eclipse Collections CharAdapterCharBag

 CharBag bag = CharAdapter.adapt("The quick brown fox jumped over the lazy dog.").toBag(); Assert.assertEquals(1, bag.occurrencesOf('a')); Assert.assertEquals(4, bag.occurrencesOf('o')); Assert.assertEquals(8, bag.occurrencesOf(' ')); Assert.assertEquals(1, bag.occurrencesOf('.')); 

注意:我是Eclipse Collections的提交者

您也可以通过遍历String并使用switch检查每个单独的字符,在找到匹配项时添加计数器来实现它。 啊,也许一些代码会让它更清晰:

主要用途:

 public static void main(String[] args) { String test = "The quick brown fox jumped over the lazy dog."; int countA = 0, countO = 0, countSpace = 0, countDot = 0; for (int i = 0; i < test.length(); i++) { switch (test.charAt(i)) { case 'a': case 'A': countA++; break; case 'o': case 'O': countO++; break; case ' ': countSpace++; break; case '.': countDot++; break; } } System.out.printf("%s%d%n%s%d%n%s%d%n%s%d", "A: ", countA, "O: ", countO, "Space: ", countSpace, "Dot: ", countDot); } 

输出:

 A: 1 O: 4 Space: 8 Dot: 1 
 import java.util.HashMap; import java.util.Scanner; public class HashMapDemo { public static void main(String[] args) { //Create HashMap object to Store Element as Key and Value HashMap hm= new HashMap(); //Enter Your String From Console System.out.println("Enter an String:"); //Create Scanner Class Object From Retrive the element from console to our java application Scanner sc = new Scanner(System.in); //Store Data in an string format String s1=sc.nextLine(); //find the length of an string and check that hashmap object contain the character or not by using //containskey() if that map object contain element only one than count that value as one or if it contain more than one than increment value for(int i=0;i 

有三种方法可以找到重复项

 public class WAP_PrintDuplicates { public static void main(String[] args) { String input = "iabccdeffghhijkkkl"; findDuplicate1(input); findDuplicate2(input); findDuplicate3(input); } private static void findDuplicate3(String input) { HashMap hm = new HashMap(); for (int i = 0; i < input.length() - 1; i++) { int ch = input.charAt(i); if (hm.containsKey(input.charAt(i))) { int value = hm.get(input.charAt(i)); hm.put(input.charAt(i), value + 1); } else { hm.put(input.charAt(i), 1); } } Set> entryObj = hm.entrySet(); for (Entry entry : entryObj) { if (entry.getValue() > 1) { System.out.println("Duplicate: " + entry.getKey()); } } } private static void findDuplicate2(String input) { int i = 0; for (int j = i + 1; j < input.length(); j++, i++) { if (input.charAt(i) == input.charAt(j)) { System.out.println("Duplicate is: " + input.charAt(i)); } } } private static void findDuplicate1(String input) { // TODO Auto-generated method stub for (int i = 0; i < input.length(); i++) { for (int j = i + 1; j < input.length(); j++) { if (input.charAt(i) == input.charAt(j)) { System.out.println("Duplicate is: " + input.charAt(i)); } } } } } 
 public class dublicate { public static void main(String...a) { System.out.print("Enter the String"); Scanner sc=new Scanner(System.in); String st=sc.nextLine(); int [] ar=new int[256]; for(int i=0;i0) { if(ar[i]==1) { System.out.print(ch); } else { System.out.print(ch+""+ar[i]); } } } } } 

如果你的字符串只包含字母表,那么你可以使用这样的东西。

 public class StringExample { public static void main(String[] args) { String str = "abcdabghplhhnfl".toLowerCase(); // create a integer array for 26 alphabets. // where index 0,1,2.. will be the container for frequency of a,b,c... Integer[] ar = new Integer[26]; // fill the integer array with character frequency. for(int i=0;i1) { char c = (char) (97+i); System.out.println("'"+c+"' comes "+ar[i]+" times."); } } } } 

输出:

  'a' comes 2 times. 'b' comes 2 times. 'h' comes 3 times. 'l' comes 2 times. 
 import java.util.HashMap; import java.util.Map; import java.util.Scanner; import java.util.Set; public class DuplicateCountChar{ public static void main(String[] args) { Scanner inputString = new Scanner(System.in); String token = inputString.nextLine(); char[] ch = token.toCharArray(); Map dupCountMap = new HashMap(); for (char c : ch) { if(dupCountMap.containsKey(c)) { dupCountMap.put(c, dupCountMap.get(c)+1); }else { dupCountMap.put(c, 1); } } for (char c : ch) { System.out.println("Key = "+c+ "Value : "+dupCountMap.get(c)); } Set keys = dupCountMap.keySet(); for (Character character : keys) { System.out.println("Key = "+character+ " Value : " + dupCountMap.get(character)); } }** 

在java …使用for循环:

 import java.util.Scanner; /** * * @author MD SADDAM HUSSAIN */ public class Learn { public static void main(String args[]) { Scanner sc = new Scanner(System.in); String input = sc.next(); char process[] = input.toCharArray(); boolean status = false; int index = 0; for (int i = 0; i < process.length; i++) { for (int j = 0; j < process.length; j++) { if (i == j) { continue; } else { if (process[i] == process[j]) { status = true; index = i; break; } else { status = false; } } } if (status) { System.out.print("" + process[index]); } } } } 
  public class StringCountwithOutHashMap { public static void main(String[] args) { System.out.println("Plz Enter Your String: "); Scanner sc = new Scanner(System.in); String s1 = sc.nextLine(); int count = 0; for (int i = 0; i < s1.length(); i++) { for (int j = 0; j < s1.length(); j++) { if (s1.charAt(i) == s1.charAt(j)) { count++; } } System.out.println(s1.charAt(i) + " --> " + count); String d = String.valueOf(s1.charAt(i)).trim(); s1 = s1.replaceAll(d, ""); count = 0; }}} 
 public class CountH { public static void main(String[] args) { String input = "Hi how are you"; char charCount = 'h'; int count = 0; input = input.toLowerCase(); for (int i = 0; i < input.length(); i++) { if (input.charAt(i) == charCount) { count++; } } System.out.println(count); } } 
 public class DuplicateValue { public static void main(String[] args) { String s = "hezzz"; char []st=s.toCharArray(); int count=0; Set ch=new HashSet<>(); for(Character cg:st){ if(ch.add(cg)==false){ int occurrences = Collections.frequency(ch, cg); count+=occurrences; if(count>1){ System.out.println(cg + ": This character exist more than one time"); } else{ System.out.println(cg); } } } System.out.println(count); } } 
  Map listMap = new HashMap(); Scanner in= new Scanner(System.in); System.out.println("enter the string"); String name=in.nextLine().toString(); Integer value=0; for(int i=0;i 
 import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); String reverse1; String reverse2; int count = 0; while(n > 0) { String A = sc.next(); String B = sc.next(); reverse1 = new StringBuffer(A).reverse().toString(); reverse2 = new StringBuffer(B).reverse().toString(); if(!A.equals(reverse1)) { for(int i = 0; i < A.length(); i++) { for(int j = 0; j < A.length(); j++) { if(A.charAt(j) == A.charAt(i)) { count++; } } if(count % 2 != 0) { A.replace(A.charAt(i),""); count = 0; } } System.out.println(A); } n--; } } } 
 public class list { public static String name(Character k){ String s="the quick brown fox jumped over the lazy dog."; int count=0; String l1=""; String l=""; List list=new ArrayList(); for(int i1=0;i1 

String查找重复项:

示例1:使用HashMap

 public class a36 { public static void main(String[] args) { String a = "Gini Rani"; fix(a); }//main public static void fix(String a ){ Map map = new HashMap<>(); for (int i = 0; i  list = new ArrayList<>(); Set > entrySet = map.entrySet(); for ( Map.Entry entry : entrySet) { list.add( entry.getKey() ); System.out.printf( " %s : %d %n" , entry.getKey(), entry.getValue() ); }//for System.out.println("Duplicate elements => " + list); }//fix } 

示例2:在Java 8中使用Arrays.stream()

 public class a37 { public static void main(String[] args) { String aa = "Protijayi Gini"; String[] stringarray = aa.split(""); Map map = Arrays.stream(stringarray) .collect(Collectors.groupingBy(c -> c , Collectors.counting())); map.forEach( (k, v) -> System.out.println(k + " : "+ v) ); } } 
 public static void main(String[] args) { char[] array = "aabsbdcbdgratsbdbcfdgs".toCharArray(); char[][] countArr = new char[array.length][2]; int lastIndex = 0; for (char c : array) { int foundIndex = -1; for (int i = 0; i < lastIndex; i++) { if (countArr[i][0] == c) { foundIndex = i; break; } } if (foundIndex >= 0) { int a = countArr[foundIndex][1]; countArr[foundIndex][1] = (char) ++a; } else { countArr[lastIndex][0] = c; countArr[lastIndex][1] = '1'; lastIndex++; } } for (int i = 0; i < lastIndex; i++) { System.out.println(countArr[i][0] + " " + countArr[i][1]); } } 
 //sample Input /*2 7 saska toro winn toro vanco saska toro 3 edddddd edddddd edddddd*/ //sample output /*4 1*/ import java.util.ArrayList; import java.util.Scanner; public class MyTestWhere { /** * @param args */ public static void main(String[] args) { int count, line; Scanner sn = new Scanner(System.in); count = sn.nextInt(); sn.nextLine(); for (int i = 0; i < count; i++) { line = sn.nextInt(); sn.nextLine(); // String numArr[] = new String[line]; ArrayList Arr=new ArrayList(); String first = sn.nextLine(); Arr.add(first);String f; for (int j = 1; j < line; j++) { f= sn.nextLine(); for(int k=0;k 
 public static void findDuplicate(String letter) { for(int i=0; i 

findDuplicate( “JAVA”);

OUTPUT是:A

 import java.util.Scanner; class Test { static String s2=""; int l; void countDuplicateCharacters(String Str) { String S=Str.toLowerCase(); for(int i=0;i