简体   繁体   English

如何使用switch循环计算字符串中的多个字符出现次数? Java的

[英]How to count multiple character occurrences in a string using the switch loop? Java

Looking to count the letters a, e, s, t also the upper case. 想要计算字母a,e,s,t也是大写字母。 Using the switch loop. 使用开关循环。 I have already have it so it counts the blank spaces but I dont know how to setup the switch and how to print it. 我已经拥有它所以它计算空白但我不知道如何设置开关以及如何打印它。 Thank you 谢谢

import java.util.Scanner;

public class Count {
    public static void main(String[] args) {
        String phrase;   // a string of characters
        int countBlank;  // the number of blanks (spaces) in the phrase
        int length;      // the length of the phrase
        char ch;         // an individual character in the string

        Scanner scan = new Scanner(System.in);
        // Print a program header
        System.out.println();
        System.out.println("Character Counter");
        System.out.println();
        // Read in a string and find its length
        System.out.print("Enter a sentence or phrase: ");
        phrase = scan.nextLine();
        length = phrase.length();
        // Initialize counts
        countBlank = 0;
        // a for loop to go through the string character by character
        // and count the blank spaces
        // Print the results System.out.println ();
        for (int i = 0; i < phrase.length(); i++) {
            if (Character.isWhitespace(phrase.charAt(i))) {
                countBlank++;
            }
        }
        ch = phrase.charAt(phrase.length());

        System.out.println();

        System.out.println("Number of blank spaces: " + countBlank);

        System.out.println();
    }
}

I think this might be helpful, 我认为这可能会有所帮助,

import java.util.Scanner;
class Count {
    public static void main(String[] args) {
        String phrase;   // a string of characters
        int countBlank;  // the number of blanks (spaces) in the phrase
        int length;      // the length of the phrase
        char ch;         // an individual character in the string


        phrase = "abcd efgh skjadh sjds";
        length = phrase.length();
        int i = 0;
        // Initialize counts
        countBlank = 0;
        // a for loop to go through the string character by character
        // and count the blank spaces
        // Print the results System.out.println ();
        int aCount = 0;
        int eCount = 0;
        int sCount = 0;
        int tCount = 0;
        int capACount = 0;
        int capECount = 0;
        int capSCount = 0;
        int capTCount = 0;
        while(i < length) {
            ch = phrase.charAt(i);
            switch(ch) {
                case 'a' :
                    aCount++;
                    break;
                case 'e' : 
                    eCount++;
                    break;
                case 's' :
                    sCount++;
                    break;
                case 't' : 
                    tCount++;
                    break;
                case 'A' :
                    capACount++;
                    break;
                case 'E' :
                    capECount++;
                    break;
                case 'S' :
                    capSCount++;
                    break;
                case 'T' :
                    capTCount++;
                    break;

            }
            i++;
        }

        System.out.println("Number of a: " + aCount);
        System.out.println("Number of e: " + eCount);
        System.out.println("Number of s: " + sCount);
        System.out.println("Number of t: " + tCount);
        System.out.println("Number of A: " + capACount);
        System.out.println("Number of E: " + capECount);
        System.out.println("Number of S: " + capSCount);
        System.out.println("Number of T: " + capTCount);

    }
}

How about using the JDK instead: 如何使用JDK代替:

int countBlank = phrase.length() - phrase.replace(" ", "").length();
int countAest = phrase.length() - phrase.replaceAll("(?i)[aest]", "").length();

These two lines work by removing the characters of interest then using the change in length to give you the count. 这两行的工作方式是删除感兴趣的字符,然后使用长度的变化来计算。

FYI, in regex, (?i) means "ignore case", and [aest] means "any of the characters a, e, s or t". 仅供参考,在正则表达式中, (?i)表示“忽略大小写”, [aest]表示“任何字符a,e,s或t”。

Consider putting the characters you want to find in a String also. 考虑将要查找的String也放在String This way you can use the charAt() method on the input phrase as well as the string of characters you want to find. 这样,您可以对输入phrase使用charAt()方法以及要查找的字符串。

    public static void main(String[] args) {
        // Print a program header
        System.out.println();
        System.out.println("Character Counter");
        System.out.println();

        // Read in a string and find its length
        System.out.print("Enter a sentence or phrase: ");
        Scanner scan = new Scanner(System.in);
        String phrase = scan.nextLine();
        int length = phrase.length();

        // Initialize counts
        String findChars = " AaEeSsTt"; // we will count each of these characters
        int[] counts = new int[findChars.length()]; // the counts of findChars

        // Go through the string character by character and count findChars
        for (int i = 0; i < length; i++) {
            char ch = phrase.charAt(i);
            for (int n = 0; n < findChars.length(); n++) {
                char find = findChars.charAt(n);
                if (ch == find) {
                    counts[n]++;
                    break;
                }
            }
        }
        System.out.println();

        // Print the results to System.out
        for (int n = 0; n < findChars.length(); n++) {
            System.out.println("Number of '"
                + findChars.charAt(n) + "': " + counts[n]);
        }
        System.out.println();
    }

In the example below, first we taking one sentence as String , which we will read Character by Character , and as we read each Character we will increment (respective index value), for int Array , like: 在下面的例子中,首先我们将一个句子作为String ,我们将读取Character by Character ,当我们读取每个Character我们将增加(相应的索引值),对于int Array ,如:

int value = ( int ) sentence.charAt (i);
characterCount [value]++;

If only you knew, that you reading ASCII character set, then you can use this approach too, or modify it to suit the needs of the project. 如果只知道您读取ASCII字符集,那么您也可以使用这种方法,或者修改它以满足项目的需要。

public class AlphabetCountingExample {

    private static final int TOTAL_ASCII_CHARACTERS = 256;
    private String sentence;
    private int [] characterCount;

    public AlphabetCountingExample () {
        characterCount = new int [TOTAL_ASCII_CHARACTERS];
        sentence = "Hello there!!!";
    }

    private void performTask () {
        countCharacters ();     
        displayCount ();
    }

    private void countCharacters () {
        for ( int i = 0; i < sentence.length (); ++i ) {
            int value = ( int ) sentence.charAt (i);
            characterCount [value]++;
        }
    }

    private void displayCount () {
        for ( int i = 0; i < characterCount.length; ++i ) {
            if ( characterCount [ i ] > 0 ) {
                System.out.println ( "Character: " + (char) i +
                                " Count: " + characterCount [ i ] );
            }
        }
    }

    public static void main (String[] args) {
        new AlphabetCountingExample ().performTask ();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM