1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | public class ParToSent { public static void main(String[] args){ String st="Each programming language has its own advantages and disadvantages. A wide variety of open source applications are written in PHP. ASP offers a much smaller learning curve. JSP provides all the features of Java."; //Counting the number of sentences in the paragraph. int counter=0; for(int i=0;i<st.length();i++){ if(st.charAt(i)=='.'){ counter++; } } String[] sent=new String[counter]; String stemp=st; int firstindex=0; for(int i=0;i<sent.length;i++){ int lastindex=stemp.indexOf('.'); sent[i]=stemp.substring(firstindex,lastindex).trim(); stemp=stemp.substring(lastindex+1); } for(int i=0;i<sent.length;i++){ System.out.println(sent[i]); } } } |
The variable counter holds the number of sentences in the paragraph. It is used for array declaration.
int lastindex=stemp.indexOf('.');
This code finds the index of the last character ('.') of each sentence. The result is stored in the variable lastindex.
sent[i]=stemp.substring(firstindex,lastindex).trim();
When the last index of the first sentence is found, the sentence will be taken from the paragraph and stored in an array. substring() method is used for this purpose. Using the for( ; ; ;) statement, this occurs until the last sentence in the paragraph is found and stored in the array. The trim() method eliminates whitespaces in the sentence.
stemp=stemp.substring(lastindex+1);
Everytime a sentence is found and stored in the array, it will be removed from the paragraph. The second sentence becomes the first. The third becomes the second, and so on. The last index of the first sentence therefore changes.
System.out.println(sent[i]);
Finally, all the sentences stored in the array are displayed on the screen.
No comments:
Post a Comment