使用Java查找字符串中的重复字符并计算发生的次数
如何查找字符串中字符的出现次数 例如:敏捷的棕色狐狸跳过了懒狗 以下是一些示例输出:使用Java查找字符串中的重复字符并计算发生的次数,java,Java,如何查找字符串中字符的出现次数 例如:敏捷的棕色狐狸跳过了懒狗 以下是一些示例输出: 'a' = 1 'o' = 4 'space' = 8 '.' = 1 如果字符串s是要处理的字符串,则可以使用以下命令 Map<Character,Integer> map = new HashMap<Character,Integer>(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if
'a' = 1
'o' = 4
'space' = 8
'.' = 1
如果字符串
s
是要处理的字符串,则可以使用以下命令
Map<Character,Integer> map = new HashMap<Character,Integer>();
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);
}
}
Map Map=newhashmap();
对于(int i=0;i
注意,它将计算所有字符,而不仅仅是字母。更好的方法是创建一个用于存储计数的。那将是一张
地图
您需要迭代字符串的每个字符,并检查其是否为字母表。你可以用这个方法。如果它是字母表
,则增加其在地图中的计数
。如果字符不在映射中
,则添加计数为1的字符
注意:-字符.isAlphabetic
方法是Java7
中的新方法。如果您使用的是旧版本,则应使用
使用谷歌番石榴Multiset
Multiset单词Multiset=HashMultiset.create();
wordsMultiset.addAll(单词);
for(Multiset.Entry:wordsMultiset.entrySet()){
System.out.println(entry.getElement()+“-”+entry.getCount());
}
void Findrepeter(){
字符串s=“mmababctmantlslmag”;
int=0;
对于(int i=0;i
导入java.util.HashMap;
导入java.util.Scanner;
公共类HashMapDemo{
公共静态void main(字符串[]args){
//创建HashMap对象以将元素存储为键和值
HashMap hm=新的HashMap();
//从控制台输入您的字符串
System.out.println(“输入字符串:”);
//创建Scanner类对象,将元素从控制台检索到java应用程序
扫描仪sc=新的扫描仪(System.in);
//以字符串格式存储数据
字符串s1=sc.nextLine();
//查找字符串的长度,并通过使用检查hashmap对象是否包含该字符
//containskey(),如果该映射对象只包含一个以上的元素,则将该值计为一,或者如果该映射对象包含多个以上的增量值
对于(int i=0;ipublicstaticvoidmain(String[]args){
char[]array=“aabsbdcbdgratsbdbcfdgs”.toCharArray();
char[][]countArr=新字符[array.length][2];
int lastIndex=0;
for(字符c:数组){
int foundIndex=-1;
对于(int i=0;i=0){
int a=countArr[foundIndex][1];
countArr[foundIndex][1]=(字符)++a;
}否则{
countArr[lastIndex][0]=c;
countArr[lastIndex][1]=“1”;
lastIndex++;
}
}
对于(int i=0;i
//示例输入
/*2
7.
萨斯卡
托罗
温恩
托罗
万科
萨斯卡
托罗
3.
EDDDDD
EDDDDD
EDDDDD*/
//样本输出
/*4
1*/
导入java.util.ArrayList;
导入java.util.Scanner;
公共类MyTestWhere{
/**
*@param args
*/
公共静态void main(字符串[]args){
整数计数,行;
扫描仪序列号=新扫描仪(System.in);
count=sn.nextInt();
sn.nextLine();
对于(int i=0;iimport java.util.HashMap;
导入java.util.Map;
导入java.util.Scanner;
导入java.util.Set;
公共类DuplicateCountChar{
公共静态void main(字符串[]args){
扫描仪输入字符串=新扫描仪(System.in);
字符串标记=inputString.nextLine();
char[]ch=token.toCharArray();
Map dupCountMap=新HashMap();
for(字符c:ch){
if(dupCountMap.containsKey(c)){
dupCountMap.put(c,dupCountMap.get(c)+1);
}否则{
dupCountMap.put(c,1);
}
}
for(字符c:ch){
System.out.println(“Key=“+c+”值:“+dupCountMap.get(c));
}
Set keys=dupCountMap.keySet();
用于(字符:关键点){
System.out.println(“Key=“+character+”值:“+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]);
}
}
}
}
import java.util.Scanner;
/**
*
*@作者萨达姆·侯赛因博士*/
公共课堂学习{
公共静态void main(字符串参数[]){
扫描仪sc=新的扫描仪(System.in);
字符串输入=sc.next();
char进程[]=input.toCharArray();
布尔状态=假;
int指数=0;
for(int i=0;iMap<Character,Integer> map = new HashMap<Character,Integer>();
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);
}
}
String str = "asdfasdfafk asd234asda";
Map<Character, Integer> charMap = new HashMap<Character, Integer>();
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}
Multiset<String> wordsMultiset = HashMultiset.create();
wordsMultiset.addAll(words);
for(Multiset.Entry<E> entry:wordsMultiset.entrySet()){
System.out.println(entry.getElement()+" - "+entry.getCount());
}
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.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<Character,Integer> hm= new HashMap<Character,Integer>();
//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<s1.length();i++){
if(!hm.containsKey(s1.charAt(i))){
hm.put(s1.charAt(i),(Integer)1);
}//if
else{
hm.put(s1.charAt(i),hm.get(s1.charAt(i))+1);
}//else
}//for
System.out.println("The Charecters are:"+hm);
}//main
}//HashMapDemo
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<String> Arr=new ArrayList<String>();
String first = sn.nextLine();
Arr.add(first);String f;
for (int j = 1; j < line; j++) {
f= sn.nextLine();
for(int k=0;k<Arr.size();k++){
if(f.equalsIgnoreCase(Arr.get(k)))break;
else if(k== (Arr.size()-1)){Arr.add(f);}
}
}
System.out.println(Arr.size());
}
}
}
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<Character, Integer> dupCountMap = new HashMap<Character,Integer>();
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<Character> keys = dupCountMap.keySet();
for (Character character : keys) {
System.out.println("Key = "+character+ " Value : " + dupCountMap.get(character));
}
}**
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]);
}
}
}
}
"The quick brown fox jumped over the lazy dog."
.chars()
.mapToObj(i -> (char) i)
.collect(Collectors.groupingBy(Object::toString, Collectors.counting()));
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 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<Character, Integer> map = new HashMap<Character, Integer>();
for(char val:arr){
map.put(val,map.containsKey(val)?map.get(val)+1:1);
}
for (Entry<Character, Integer> entry : map.entrySet()) {
if(entry.getValue()>1){
Character key = entry.getKey();
Object value = entry.getValue();
System.out.println(key + ":"+value);
}
}
}
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 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);
}
public static void main(String[] args){
A.getDuplicates("mymgsgkkabcdyy");
}
public class DuplicateValue {
public static void main(String[] args) {
String s = "hezzz";
char []st=s.toCharArray();
int count=0;
Set<Character> 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);
}
}
CharBag bag =
Strings.asChars("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('.'));
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
Map<Character,Integer> listMap = new HashMap<Character,Integer>();
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<name.length();i++){
if(i==0){
listMap.put(name.charAt(0), 1);
}
else if(listMap.containsKey(name.charAt(i))){
value=listMap.get(name.charAt(i));
listMap.put(name.charAt(i), value+1);
}else listMap.put(name.charAt(i),1);
}
System.out.println(listMap);
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<Character, Integer> hm = new HashMap<Character, Integer>();
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<Entry<Character, Integer>> entryObj = hm.entrySet();
for (Entry<Character, Integer> 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;i<st.length();i++)
{
ar[st.charAt(i)]=ar[st.charAt(i)]+1;
}
for(int i=0;i<256;i++)
{
char ch=(char)i;
if(ar[i]>0)
{
if(ar[i]==1)
{
System.out.print(ch);
}
else
{
System.out.print(ch+""+ar[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--;
}
}
}
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
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;i<str.length();i++) {
int j = str.charAt(i) -'a';
if(ar[j]==null) {
ar[j]= 1;
}else {
ar[j]+= 1;
}
}
// print only those alphabets having frequency greater then 1.
for(int i=0;i<ar.length;i++) {
if(ar[i]!=null && ar[i]>1) {
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.
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<Character> list=new ArrayList<Character>();
for(int i1=0;i1<s.length();i1++){
list.add(s.charAt(i1));
}
list.sort(null);
for (Character character : list) {
l+=character;
}
for (int i1=0;i1<l.length();i1++) {
if((l.charAt(i1)==k)){
count+=1;
l1=l.charAt(i1)+" "+Integer.toString(count);
if(k==' '){
l1="Space"+" "+Integer.toString(count);
}
}else{
count=0;
}
}
return l1;
}
public static void main(String[] args){
String g = name('.');
System.out.println(g);
}
}
public class a36 {
public static void main(String[] args) {
String a = "Gini Rani";
fix(a);
}//main
public static void fix(String a ){
Map<Character ,Integer> map = new HashMap<>();
for (int i = 0; i <a.length() ; i++ ) {
char ch = a.charAt(i);
map.put(ch , map.getOrDefault(ch,0) +1 );
}//for
List<Character> list = new ArrayList<>();
Set<Map.Entry<Character ,Integer> > entrySet = map.entrySet();
for ( Map.Entry<Character ,Integer> entry : entrySet) {
list.add( entry.getKey() );
System.out.printf( " %s : %d %n" , entry.getKey(), entry.getValue() );
}//for
System.out.println("Duplicate elements => " + list);
}//fix
}
public class a37 {
public static void main(String[] args) {
String aa = "Protijayi Gini";
String[] stringarray = aa.split("");
Map<String , Long> map = Arrays.stream(stringarray)
.collect(Collectors.groupingBy(c -> c , Collectors.counting()));
map.forEach( (k, v) -> System.out.println(k + " : "+ v) );
}
}
import java.util.Scanner;
class Test
{
static String s2="";
int l;
void countDuplicateCharacters(String Str)
{
String S=Str.toLowerCase();
for(int i=0;i<S.length();i++)
{
int k=1;
boolean value= repeatedCheck(S.charAt(i));
if(value==true)
continue;
for(int j=i+1;j<S.length();j++)
{
if(S.charAt(i)==S.charAt(j))
{ k++;
}
}
System.out.println("character '" +S.charAt(i)+"' : "+k);
s2=s2+S.charAt(i);
}
}
boolean repeatedCheck(char ch)
{
l=s2.length();
for (int i=0;i<l;i++)
{
if(s2.charAt(i)==ch)
{
return true;
}
}
return false;
}
}
public class Duplicacy {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter any String");
String s=sc.nextLine();
Test t=new Test();
t.countDuplicateCharacters(s);
}}
int[][] arr = new int[10][2];
String st = "aaaabbbcdefggggh";
char[] stArr = st.toCharArray();
int i = 0;
int j = 0;
for (int k = 0; k < stArr.length; k++) {
if (k == 0) {
arr[i][j] = stArr[k];
arr[i][j + 1] = 1;
} else {
if (arr[i][j] == stArr[k]) {
arr[i][j + 1] = arr[i][j + 1] + 1;
} else {
arr[++i][j] = stArr[k];
arr[i][j + 1] = 1;
}
}
}
System.out.print(arr.length);
String output = "";
for (int m = 0; m < arr.length; m++) {
if (arr[m][1] > 0) {
String character = Character.toString((char) arr[m][0]);
String cnt = arr[m][1] > 1 ? String.valueOf(arr[m][1]) : "";
output = output + character + cnt;
}
}
System.out.print(output);
void findOccurrences() {
String s = "The quick brown fox jumped over the lazy dog.";
Map<String, Integer> occurrences = new LinkedHashMap<String, Integer>();
for (String ch : s.split("")) {
Integer count = occurrences.get(ch);
occurrences.put(ch, count == null ? 1 : count + 1);
}
System.out.println(occurrences);
}