0

I am writing a code in java which asks me to find the number of characters in sentence 1, sentence 2 and till the last sentence until the string/paragraph ends. I am actually able to get the number of characters in the whole string. But what i am supposed to get is how many characters are there in each sentence, inside a paragraph. For example inside a paragraph, the first sentence has 70 characters , second have 40 and so on. i think its related with period ending but don't know how to execute it.

3 Answers3

0

check this out:

String s = "I got it. i seriously got 99.99% of it. never mind the remaining 0.01%";
String[] arrs = s.split("\\. ");
for(String str : arrs) {
    System.out.println(str);
}

above code results in this result:

I got it
i seriously got 99.99% of it
never mind the remaining 0.01% 

thus, I am able to split the whole paragraph in to sentences by spliting the given string where ever there is a match of full-stop and a space i.e sentence termination. s.split("\\. ") is the code responsible for that. i used \\ to escape a . which holds special significance in regex.

you can do something like:

String[] arrs = s.split("\\. ");
for(String str : arrs) {
    int charCount = str.toCharArray().length;
    System.out.println(charCount); //prints size of sentence "str"
}
AppleCiderGuy
  • 1,249
  • 1
  • 9
  • 16
0

Just loop through the string and divide it into substrings separated by \n (symbol for new paragraph) Here's a link with more info on how it works. https://codingbat.com/doc/java-string-indexof-parsing.html

 int i = 0;
 while(myString.indexOf("\n", i) != -1) {
     //Divides the main string into each paragraph
     String mySubstring = myString.substring(myString.indexOf("\n", i-1), myString.indexOf("\n", i));
     //Prints out length of each paragraph
     System.out.println(mySubstring.length());
     i++;
 }
Pedro
  • 1
  • 1
  • 2
0

You can take your paragraph and split it at a dot followed by any blank character and save it into a string array.
Then loop over the array and count the letters of each sentence.

String paragraph = "This is the first sentence. And this the second one. A third one follows.";

String[] sentences = paragraph.split("\\.\\s");
for(int i = 0; i < sentences.length; i++) {
    System.out.println(String.format("Sentence %d has %d characters", i + 1, sentences[i].length()));
}

Which gives you the following output:

Sentence 1 has 26 characters
Sentence 2 has 23 characters
Sentence 3 has 20 characters

Be aware that this doesn't cover a sentence containing e. g. Mr. or any abbreviations.

oemel09
  • 744
  • 7
  • 15