Java 我想显示字符串中出现的字符。如何改进代码?

Java 我想显示字符串中出现的字符。如何改进代码?,java,string,count,find-occurrences,Java,String,Count,Find Occurrences,我想创建一个程序,该程序将显示字符串中字符的出现次数,并对其进行计数。现在代码只计算字符数 我想做以下更改: 1) 我如何让这个程序只计算一种类型的字符,比如字符串中的a或c,我喜欢冰淇淋 2) 我如何也打印字符串中的字符,假设有两个d我的程序将首先显示2d 3) 对于扫描仪输入=新扫描仪(System.in)我在eclipse中遇到错误的部分说,扫描仪无法解析为类型 也可以随意评论代码中任何需要改进的地方。基本上只需要一个简单的程序来显示字符串中的所有C,然后计算字符串的出现次数。然后我想自己

我想创建一个程序,该程序将显示字符串中字符的出现次数,并对其进行计数。现在代码只计算字符数

我想做以下更改:

1) 我如何让这个程序只计算一种类型的字符,比如字符串中的
a
c
我喜欢冰淇淋

2) 我如何也打印字符串中的字符,假设有两个
d
我的程序将首先显示2
d

3) 对于
扫描仪输入=新扫描仪(System.in)我在eclipse中遇到错误的部分说,扫描仪无法解析为类型

也可以随意评论代码中任何需要改进的地方。基本上只需要一个简单的程序来显示字符串中的所有C,然后计算字符串的出现次数。然后我想自己动手修改代码,这样我就可以学习Java了

这是我到目前为止的代码:

public class Count { 
    static final int MAX_CHAR = 256; //is this part even needed?

    public static void countString(String str) 
    { 
        // Create an array of size 256 i.e. ASCII_SIZE 
        int count[] = new int[MAX_CHAR]; 

        int length = str.length(); 

        // Initialize count array index 
        for (int i = 0; i < length; i++) 
            count[str.charAt(i)]++; 

        // Create an array of given String size 
        char ch[] = new char[str.length()]; 
        for (int i = 0; i < length; i++) { 
            ch[i] = str.charAt(i); 
            int find = 0; 
            for (int j = 0; j <= i; j++) { 

                // If any matches found 
                if (str.charAt(i) == ch[j])  
                    find++;                 
            } 

            if (find == 1)  
                System.out.println("Number of Occurrence of " + 
                 str.charAt(i) + " is:" + count[str.charAt(i)]);             
        } 
    } 
    public static void main(String[] args) { 
        Scanner input = new Scanner(System.in); 
        String str = "geeksforgeeks"; 
        countString(str); 
    } 
} 
公共类计数{
静态final int MAX_CHAR=256;//甚至需要这个部分吗?
公共静态void countString(String str)
{ 
//创建大小为256的数组,即ASCII_大小
int count[]=新int[MAX_CHAR];
int length=str.length();
//初始化计数数组索引
for(int i=0;i对于(int j=0;j,您可以利用每个字符都可以用作数组的索引这一事实,并使用数组对每个字符进行计数

public class Count {
static final int MAX_CHAR = 256; 

    private static void countString(String str, Character character) {
        int [] counts = new int[MAX_CHAR];
        char [] chars = str.toCharArray();
        for (char ch : chars) {
            if (character!=null && character!=ch) {
                continue;
            }
            counts[ch]++;
        }
        for (int i=0; i<counts.length; i++) {
            if (counts[i]>0) {
                System.out.println("Character " + (char)i + " appeared " + counts[i] + " times");
            }
        }
    }
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        String str = input.nextLine();
        countString(str, 'e');
    }
}
公共类计数{
静态最终int MAX_CHAR=256;
私有静态void countString(字符串str,字符){
int[]计数=新的int[MAX_CHAR];
char[]chars=str.toCharArray();
for(char ch:chars){
if(character!=null&&character!=ch){
继续;
}
计数[ch]++;
}
对于(int i=0;i0){
System.out.println(“字符”+(字符)i+“出现”+计数[i]+“次数”);
}
}
}
公共静态void main(字符串[]args){
扫描仪输入=新扫描仪(System.in);
String str=input.nextLine();
countString(str,'e');
}
}
  • 您可以从用户“他/她想要计数的字符”处获取输入。
  • 要显示字符的出现,请参见下面的代码
  • 您需要导入java.util.Scanner类
  • 这是您的代码:

    import java.util.Arrays;
    import java.util.Scanner;
    
    public class Count { 
    
        public static void countString(String str) 
        { 
    
            if(str!=null) {
                int length = str.length(); 
    
                // Create an array of given String size 
                char ch[] = str.toCharArray();
                Arrays.sort(ch);
                if(length>0) {
                    char x = ch[0];
                    int count = 1;
                    for(int i=1;i<length; i++) {
                        if(ch[i] == x) {
                            count++;
                        } else {
                            System.out.println("Number of Occurrence of '" + 
                                     ch[i-1] + "' is: " + count);
                            x= ch[i];
                            count = 1;
                        }
                    }
                    System.out.println("Number of Occurrence of '" + 
                         ch[length-1] + "' is: " + count);
                }
            }
        } 
        public static void main(String[] args) { 
            Scanner input = new Scanner(System.in); 
            String str =  input.nextLine();//"geeksforgeeks"; 
            countString(str); 
        } 
    } 
    
    导入java.util.array;
    导入java.util.Scanner;
    公共类计数{
    公共静态void countString(String str)
    { 
    如果(str!=null){
    int length=str.length();
    //创建给定字符串大小的数组
    char ch[]=str.toCharArray();
    数组。排序(ch);
    如果(长度>0){
    char x=ch[0];
    整数计数=1;
    
    对于(inti=1;i,请参阅下面的代码片段,以了解在Java8中执行此操作的方法

    public static void main(String[] args) {
        // printing all frequencies
        getCharacterFrequency("test")
                .forEach((key,value) -> System.out.println("Key : " + key + ", value: " + value));
    
        // printing frequency for a specific character
        Map<Character, Long> frequencies = getCharacterFrequency("test");
        Character character = 't';
        System.out.println("Frequency for t: " +
                (frequencies.containsKey(character) ? frequencies.get(character): 0));
    }
    
    public static final Map<Character, Long> getCharacterFrequency(String string){
        if(string == null){
            throw new RuntimeException("Null string");
        }
        return string
                 .chars()
                 .mapToObj(c -> (char) c)
                 .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
    
    }
    
    publicstaticvoidmain(字符串[]args){
    //打印所有频率
    getCharacterFrequency(“测试”)
    .forEach((键,值)->System.out.println(“键:+key+”,值:+value));
    //特定字符的打印频率
    映射频率=getCharacterFrequency(“测试”);
    字符='t';
    System.out.println(“t的频率:+
    (frequencies.containsKey(字符)?frequencies.get(字符):0);
    }
    公共静态最终映射getCharacterFrequency(字符串){
    if(字符串==null){
    抛出新的RuntimeException(“空字符串”);
    }
    返回字符串
    .chars()
    .mapToObj(c->(char)c)
    .collect(Collectors.groupingBy(Function.identity()、Collectors.counting());
    }
    
    您只需修改这行代码:

    使用
    for loop
    ,在
    if
    语句中打印
    str.charAt(i)
    for
    count[str.charAt(i)

        if (find == 1) { 
           for(int k=0;k< count[str.charAt(i)];k++)
              System.out.print(str.charAt(i)+",");
           System.out.println(count[str.charAt(i)]); 
        }
    

    我知道你是初学者,但如果你想尝试新版本的Java8特性,这使我们的编码生活变得简单和容易,你可以试试这个

    public class Count {
     static final int MAX_CHAR = 256;
     public static void main(String[] args)    {
         Scanner input = new Scanner(System.in); 
            String str = "geeksforgeeks"; 
            countString(str, 'e'); 
     }
     public static void countString(String str, char value) 
     { 
         List<String> l = Arrays.asList(str.split(""));
         // prints count of each character occurence in string
         l.stream().forEach(character->System.out.println("Number of Occurrence of " + 
                 character + " is:" + Collections.frequency(l, character)));
         if(!(Character.toString(value).isEmpty())) {
             // prints count of specified character in string
             System.out.println("Number of Occurrence of " + 
                     value + " is:" + Collections.frequency(l, Character.toString(value)));
         }
    
     } 
    
    试试这个

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        String str = input.nextLine();
    
        // Whatever is the input it take the first character.
        char searchKey = input.nextLine().charAt(0);
        countString(str, searchKey);
    }
    
    public static void countString(String str, char searchKey) {
        // The count show both number and size of occurrence of searchKey
        String count = ""; 
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == searchKey)
                count += str.charAt(i) + "\n";
        }
        System.out.println(count + "\nNumber of Occurrence of "
                        + searchKey + " is " + count.length() + " in string " + str);
    }
    
    publicstaticvoidmain(字符串[]args){
    扫描仪输入=新扫描仪(System.in);
    String str=input.nextLine();
    //无论输入是什么,它都会接受第一个字符。
    char searchKey=input.nextLine().charAt(0);
    countString(str,searchKey);
    }
    公共静态void countString(String str,char searchKey){
    //计数显示searchKey出现的次数和大小
    字符串计数=”;
    对于(int i=0;i
    您可以使用下面的代码

    import java.util.Scanner;
    
    public class Count {
    
        public static void main(String[] args) {
            Scanner input = new Scanner(System.in);
            String str = input.nextLine();
    
            char key = input.nextLine().charAt(0);
            countString(str, key);
        }
    
        public static void countString(String str, char searchKey) {
            int count = 0;
            for (int i = 0; i < str.length(); i++) {
                if (str.charAt(i) == searchKey)
                    count++;
            }
            System.out.println("Number of Occurrence of "
                    + searchKey + " is " + count + " in string " + str);
    
            for (int i = 0; i < count; i++) {
                System.out.println(searchKey);
            }
    
            if (count > 0) {
                System.out.println(count);
            }
        }
    }
    
    import java.util.Scanner;
    公共类计数{
    公共静态void main(字符串[]args){
    扫描仪输入=新扫描仪(System.in);
    String str=input.nextLine();
    char key=input.nextLine().charAt(0);
    countString(str,key);
    }
    公共静态void countString(String str,char searchKey){
    整数计数=0;
    对于(int i=0;i0){
    系统输出打印项次(计数);
    }
    }
    }
    
    我将创建一个如下方法:

    public static String stringCounter(String k) {
        char[] strings = k.toCharArray();
        int numStrings = strings.length;
        Map<String, Integer> m = new HashMap<String, Integer>();
        int counter = 0;
        for(int x = 0; x < numStrings; x++) {
            for(int y = 0; y < numStrings; y++) {
                if(strings[x] == strings[y]) {
                    counter++;
                }
    
            }m.put(String.valueOf(strings[x]), counter);
    
            counter = 0;
        }
        for(int x = 0; x < strings.length; x++) {
            System.out.println(m.get(String.valueOf(strings[x])) + String.valueOf(strings[x]));
        }
        return m.toString();
      }
    
    
    
    }
    
    和h
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        String str = input.nextLine();
    
        // Whatever is the input it take the first character.
        char searchKey = input.nextLine().charAt(0);
        countString(str, searchKey);
    }
    
    public static void countString(String str, char searchKey) {
        // The count show both number and size of occurrence of searchKey
        String count = ""; 
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == searchKey)
                count += str.charAt(i) + "\n";
        }
        System.out.println(count + "\nNumber of Occurrence of "
                        + searchKey + " is " + count.length() + " in string " + str);
    }
    
    import java.util.Scanner;
    
    public class Count {
    
        public static void main(String[] args) {
            Scanner input = new Scanner(System.in);
            String str = input.nextLine();
    
            char key = input.nextLine().charAt(0);
            countString(str, key);
        }
    
        public static void countString(String str, char searchKey) {
            int count = 0;
            for (int i = 0; i < str.length(); i++) {
                if (str.charAt(i) == searchKey)
                    count++;
            }
            System.out.println("Number of Occurrence of "
                    + searchKey + " is " + count + " in string " + str);
    
            for (int i = 0; i < count; i++) {
                System.out.println(searchKey);
            }
    
            if (count > 0) {
                System.out.println(count);
            }
        }
    }
    
    public static String stringCounter(String k) {
        char[] strings = k.toCharArray();
        int numStrings = strings.length;
        Map<String, Integer> m = new HashMap<String, Integer>();
        int counter = 0;
        for(int x = 0; x < numStrings; x++) {
            for(int y = 0; y < numStrings; y++) {
                if(strings[x] == strings[y]) {
                    counter++;
                }
    
            }m.put(String.valueOf(strings[x]), counter);
    
            counter = 0;
        }
        for(int x = 0; x < strings.length; x++) {
            System.out.println(m.get(String.valueOf(strings[x])) + String.valueOf(strings[x]));
        }
        return m.toString();
      }
    
    
    
    }
    
    System.out.println(stringCounter("Hello World"));
    
    1H
    1e
    3l
    3l
    2o
    1 
    1W
    2o
    1r
    3l
    1d
    { =1, r=1, d=1, e=1, W=1, H=1, l=3, o=2}
    
    Scanner scan = new Scanner(System.in);
    System.out.println("Please enter  a String: ");
    String str = scan.nextLine();
    System.out.println(stringCounter(str));
    
    Please enter  a String: 
    Hello World
    1H
    1e
    3l
    3l
    2o
    1 
    1W
    2o
    1r
    3l
    1d
    { =1, r=1, d=1, e=1, W=1, H=1, l=3, o=2}