简体   繁体   中英

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

This is what I have so far and I don't know where to go from here. (I am a beginner so please try to use simple logic for me to understand)

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

You have some redundant lines of code here. Removing the else block entirely should do the trick:

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

This is something of a spoiler, but you could use a replacement approach:

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

This just compares the length of the original text against the length of the text with all . , ? , and ! removed.

You can use streams as well

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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