This file contains 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
public class TextSpliter { | |
public List<String> splitText(String txt, int len) { | |
List<Integer> startList = new ArrayList<Integer>(); | |
List<Integer> lenList = new ArrayList<Integer>(); | |
String[] words = txt.split(" "); | |
boolean violate; | |
do { | |
violate = false; | |
int pLen0 = 3 + digits(startList.size()); //length needed for (ab/cd), not including ab. | |
int curPage = 1; | |
int curStart = 0; | |
int curLen = 0; | |
while (curStart < words.length) { | |
int curPageLenMax = len - pLen0 - digits(curPage); | |
int curPageLen = 0; | |
while (curStart + curLen < words.length && | |
((curLen == 0 && curPageLen + words[curStart + curLen].length() < curPageLenMax) || | |
(curLen > 0 && curPageLen + words[curStart + curLen].length() + 1 < curPageLenMax))) { | |
curPageLen += words[curStart + curLen].length(); | |
if (curLen > 0) { | |
curPageLen++; // space | |
} | |
curLen++; | |
} | |
if (curLen == 0) { | |
throw new Error("word is too long"); | |
} | |
if (curPage - 1 >= startList.size()) { | |
//if it's a new page, add it to the end | |
violate = true; | |
startList.add(curStart); | |
lenList.add(curLen); | |
} else if (startList.get(curPage - 1) != curStart || lenList.get(curPage - 1) != curLen) { | |
//if it's updating existing page, then update the list. | |
violate = true; | |
startList.set(curPage - 1, curStart); | |
lenList.set(curPage - 1, curLen); | |
} | |
curStart += curLen; | |
curLen = 0; | |
curPage++; | |
} | |
} while (violate); | |
List<String> rst = new ArrayList<String>(); | |
for (int i = 0; i < startList.size(); ++i) { | |
StringBuilder sb = new StringBuilder(); | |
for (int j = startList.get(i); j < startList.get(i) + lenList.get(i); ++j) { | |
if (j > startList.get(i)) { | |
sb.append(" "); | |
} | |
sb.append(words[j]); | |
} | |
int page = i + 1; | |
sb.append("(" + page + "/" + startList.size() + ")"); | |
rst.add(sb.toString()); | |
} | |
return rst; | |
} | |
//return how many digits for the number n | |
private int digits(int n) { | |
int count = 0; | |
while (n != 0) { | |
count++; | |
n /= 10; | |
} | |
return count == 0 ? 1: count; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment