135k views
1 vote
Write a static method that takes a String and returns an integer. Return the number of sentences passed in the method parameter of type String that end in a period, exclamation mark or question mark ( . ! ? ) .

User Serguzest
by
7.7k points

1 Answer

3 votes

Answer:

Step-by-step explanation:

public class SentenceCounter {

public static void main(String[] args) {

String text = "This is a sample sentence. Another sentence follows! What about a third sentence?";

int sentenceCount = countSentences(text);

System.out.println("Number of sentences: " + sentenceCount);

}

public static int countSentences(String input) {

if (input == null || input.isEmpty()) {

return 0;

}

// Using regular expression to split the input into sentences

String[] sentences = input.split("[.!?]");

// Counting the number of non-empty sentences

int count = 0;

for (String sentence : sentences) {

if (!sentence.trim().isEmpty()) {

count++;

}

}

return count;

}

}

User TMichel
by
7.4k points