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

13

如何在一个字符串中找到一个字符出现的次数?

例如:The quick brown fox jumped over the lazy dog。

以下是一些示例输出:

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

10
你尝试过什么? - Azodious
11
这是一份作业吗? - Thinhbk
34个回答

1

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

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));
                }
            }
        }
    }
}

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<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

1
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);
            }
            }
    }

1
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);
    }
}

2
为了帮助 OP 解决当前的问题,可以在回答中添加一些解释说明。 - ρяσѕρєя K

1

使用Eclipse Collections CharAdapterCharBag

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('.'));

注意:我是Eclipse Collections的提交者


1
你可以通过迭代你的字符串并使用 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

1

类 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);
}

}

class B public class B {

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

}

}


3
欢迎来到 StackOverflow!你能否解释一下你的代码,以及它与其他已经给出的答案有何不同或更好之处? - avojak

0

在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]);

            }
        }
    }
}

0
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);
    }
}

请使用格式化工具来正确编辑和格式化您的问题/答案。 句子中的代码应该格式化为 code。 非常重要的单词用 粗体,较不重要的单词用 斜体。 如果需要,还可以使用列表。 - Morse

0
                       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);

请解释一下你的示例是如何解决这个问题的,这将使它更有价值。谢谢! - Peter

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接