Reputation: 35
I have a program that takes in a string and counts the number of sentences in the string. I have it working but the one thing I can't figure out is if the sentence ends in multiple delimiters. Here is my test string "The quick brown fox jumps over the lazy dog. Wow!!!!" it should have two sentences in this string. But it's returning 4 it's essentially counting the three exclamation points at the end of Wow!!!!. We are only allowed to use what you see so I can't use an array.
This is what is in the SENTENCE_DELIMETERS = ".,::?!" variable.
Any help is appreciated.
int sentenceCount=0;
for(int i=0;i<myFile.length()-1;i++){
for(int j=0;j<SENTENCE_DELIMETERS.length();j++){
if(myFile.charAt(i)==SENTENCE_DELIMETERS.charAt(j))
sentenceCount++;
}
}
Upvotes: 3
Views: 7889
Reputation: 11
This is how I would do it:
// By Nishanth Chandradas
public class SentenceCounter {
public static void main(String[] args) {
int sentenceCount=1;
String myFile = "The quick brown fox jumps over the lazy dog. Wow!!!!";
String SENTENCE_DELIMETERS = ".,::?!";
for(int i=0;i<myFile .length()-1;i++){
for(int j=0;j<SENTENCE_DELIMETERS.length();j++){
if(myFile.charAt(i)==SENTENCE_DELIMETERS.charAt(j)){
if(myFile.charAt(i+1)==SENTENCE_DELIMETERS.charAt(j)){
sentenceCount--;}
sentenceCount++; } } }
System.out.println(sentenceCount);
}
}
Upvotes: 1
Reputation: 425033
You only need one line:
int count = str.split("[!?.:]+").length;
The plus sign causes multiple delimiters to be treated as one delimiter, thus solving your particular problem.
Note: A comma ,
is not a sentence delimiter.
If you absolutely must use your (incorrect) variable, build the regex from it:
split("[" + SENTENCE_DELIMETERS + "]+")
Upvotes: 4
Reputation: 136022
I would do it this way
String SENTENCE_DELIMETERS = "!.";
int sentenceCount = 0;
for (int i = 0; i < myFile.length() - 1; i++) {
if (SENTENCE_DELIMETERS.indexOf(myFile.charAt(i)) != -1 && i > 0 && SENTENCE_DELIMETERS.indexOf(myFile.charAt(i - 1)) != -1) {
sentenceCount++;
}
}
Upvotes: 2
Reputation: 288
If you not allowed to use Arrays or Lists and the SENTENCE_DELIMITERS is a String I would do somthing like this:
int sentenceCount=0;
int lastIndex=0;
for(int i=0;i<myFile.length();i++){
for(int j=0;j<SENTENCE_DELIMETERS.length();j++){
if(myFile.charAt(i)==SENTENCE_DELIMETERS.charAt(j)){
if(lastIndex!=i-1){
sentenceCount++;
}
lastIndex=i;
}
}
}
Upvotes: 2