我想显示字符串中某个字符的出现。我怎样才能改进我的代码?

I want to display the occurrence of a character in string. How can I improve my code?

我想创建一个程序来显示字符串中某个字符出现的次数并计算它们的数量。现在代码只计算字符数。

我想进行以下更改:

1) 如何让这个程序只计算一种类型的字符,比如字符串 I love ice cream.

中的 ac

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

3) 对于 Scanner input = new Scanner(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); 
    } 
} 

您可以利用每个字符都可以用作数组的索引这一事实,并使用数组对每个字符进行计数。

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');
    }
}
  1. 您可以听取用户 "which character he/she wants to count" 的意见。
    1. 要显示字符的出现,请参见下面的代码。
    2. 您需要导入 java.util.Scanner class.

这是您的代码:

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

请参阅下面的代码片段以了解在 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()));

}

你只需要修改这行代码:

使用 for loop,在 if 语句中打印 str.charAt(i) 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)]); 
    }

编辑:根据您的评论修改,如果您想要完整代码

  import java.util.*;

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]){  
                 //System.out.println(str.charAt(i));
                find++;  
            }                   
        } 

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

    } 
} 
public static void main(String[] args) { 
    Scanner input = new Scanner(System.in); 
    String str = "geeksfeorgeeks"; 
    str = input.nextLine();
    countString(str); 
} 
} 

输出

g,g,2
e,e,e,e,e,5
k,k,2
s,s,2
f,1
o,1
r,1

我知道你是初学者,但如果你想尝试新版本 java 8 个使我们的编码生活变得简单和轻松的功能,你可以试试这个

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 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) 
 { 
     String[] arr = str.split("");
     StringBuffer tempString = new StringBuffer();
     for(String s:arr) {
         tempString.append(s);
         for(char ch:s.toCharArray()) {
             System.out.println("Number of Occurrence of " + 
                     ch + " is:" + tempString.chars().filter(i->i==ch).count());
         }
     }
     if(!(Character.toString(value).isEmpty())) {
         StringBuffer tempString2 = new StringBuffer();
         for(String s:arr) {
             tempString2.append(s);
             for(char ch:s.toCharArray()) {
                 if(ch==value) {
                 System.out.println("Number of Occurrence of " + 
                         ch + " is:" + tempString2.chars().filter(i->i==ch).count());
                 }
             }
         } 
     }

   } 
} 

试试这个

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



}

显然和您一样,我会将一个字符串作为参数传递给 stringCounter 方法。在这种情况下,我会将 String 转换为 charArray,我还会创建一个映射以将 String 存储为键,并存储一个 Integer 以表示单个字符串在字符数组中出现的次数。变量计数器将计算单个字符串出现的次数。然后我们可以创建一个嵌套的 for 循环。外循环将遍历数组中的每个字符,内循环将它与数组中的每个字符进行比较。如果匹配,计数器将递增。嵌套循环完成后,我们可以将字符连同它在循环中出现的次数一起添加到 Map 中。然后我们可以在另一个 for 循环中打印结果,我遍历 map 和 char 数组。我们可以像您提到的那样打印字符出现的次数以及值。我们还可以 return 看起来也更干净的地图的字符串值。但是如果你不想 return 地图,你可以简单地让这个方法无效。输出应如下所示:

我通过输入字符串 "Hello world":

测试了 main 方法中的方法
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));

您必须先创建扫描仪对象,将 System.in 添加到构造函数以从键盘获取输入。然后,您可以使用打印语句提示用户输入字符串。然后,您可以创建一个 String 变量,该变量将通过调用 "Scanner.nextLine()" 方法作为值来存储 String。这将从键盘获取下一行用户输入。现在您可以将用户输入传递给我们的方法,它将以相同的方式运行。这是用户应该看到的样子:

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}