簡體   English   中英

該方法應該計算“.”、“?”或“!”的次數。 出現在文中

[英]the method is supposed to count the number of times a ‘.’, ‘?’, or ‘!” appears in the text

這是我到目前為止所擁有的,我不知道從哪里開始。 (我是初學者所以請嘗試使用簡單的邏輯讓我理解)

public static void countSentences(String text) {
    String comma = ",";
    String period = ".";
    String Question = "?";
    String ex = "!";
    text = "..,,??!!";
    int c = 0;
    for (int i = 0; i < text.length(); i++) {

        if (comma.equals(text.charAt(i)) || period.equals(text.charAt(i)) || 
            Question.equals(text.charAt(i)) || ex.equals(text.charAt(i))) {
            c += 1;
        }else {
            c += 0;
            i++;
        }
    }
}

這里有一些多余的代碼行。 完全刪除 else 塊應該可以解決問題:

public static void countSentences(String text) {
    char comma = ',';
    char period = '.';
    char Question = '?';
    char ex = '!';
    text = "..,,??!!";
    int c = 0;

    for (int i = 0; i < text.length(); i++) {
        if (comma == text.charAt(i) || period == text.charAt(i) || 
            Question == text.charAt(i) || ex == text.charAt(i)) {
            c += 1;
        }
    }
}

這有點劇透,但您可以使用替代方法:

public static int countSentences(String text) {
    return text.length() - text.replaceAll("[.?!]", "").length();
}

這只是將原始文本的長度與帶有 all 的文本長度進行比較. , ? ,和! 移除。

您也可以使用流

public static void countSentences(String text) {
    char comma = ',';
    char period = '.';
    char Question = '?';
    char ex = '!';
    String text = "..,,??!!";
    long count = text.chars().filter(ch -> ch == comma ||ch == Question ||ch == period ).count();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM