Created
June 13, 2019 04:37
-
-
Save GAM3RG33K/934837fb18c660c485b64a7d87312805 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Split a single string into multiple paragraphs based on the last | |
| * punctuation found in the substring while iterating. | |
| * | |
| * @param dataString long string which is to be divided into paragraphs | |
| * @param maxAllowedLength number of maximum characters allowed in one | |
| * paragraph. | |
| * @return list of paragraphs | |
| */ | |
| private static List<String> splitParagraph(String dataString, int maxAllowedLength) { | |
| int length = dataString.length(); | |
| //find iterations count | |
| int iterations = length / maxAllowedLength; | |
| //to fetch remainging string of paragraph even if missed. | |
| iterations++; | |
| ArrayList<String> splitStringList = new ArrayList<>(); | |
| //index for end of the previous paragraph | |
| int lastEnd = 0; | |
| for (int i = 0; i < iterations; i++) { | |
| //index of current End index of the paragraph | |
| int currentEnd = (lastEnd + maxAllowedLength | |
| >= length) ? length : lastEnd + maxAllowedLength; | |
| //get sub string based on maxAllowedLength | |
| String subString = dataString.substring(lastEnd, currentEnd); | |
| //find existing punctuation from the string | |
| char punctuation = getExisitingPunctuation(subString); | |
| //if not last ieration set last index of punctuation as currentEnd | |
| if (iterations + 1 != i) { | |
| int adjustedEndIndex = subString.lastIndexOf(punctuation); | |
| if (adjustedEndIndex != -1) { | |
| currentEnd = lastEnd + adjustedEndIndex + 1; | |
| } | |
| } | |
| //get a new substring based on the updated indices | |
| subString = dataString.substring(lastEnd, currentEnd); | |
| //add the substring to the list | |
| splitStringList.add(subString); | |
| //update lastEnd index | |
| if (currentEnd < length) { | |
| lastEnd = currentEnd + 1; | |
| } | |
| } | |
| return splitStringList; | |
| } | |
| /** | |
| * Find a valid punctuation in the given string to split it into a natural | |
| * paragraph. | |
| * | |
| * @param subString source string in which we need to find the punctuation | |
| * @return valid punctuation character from the string | |
| */ | |
| private static char getExisitingPunctuation(String subString) { | |
| char punctuation = '.'; | |
| if (subString.contains(",")) { | |
| return ','; | |
| } | |
| if (subString.contains("!")) { | |
| return '!'; | |
| } | |
| if (subString.contains("?")) { | |
| return '?'; | |
| } | |
| return punctuation; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment