Skip to content

Instantly share code, notes, and snippets.

@Wicowyn
Created September 7, 2015 13:09
Show Gist options
  • Save Wicowyn/3abdfe1a563e26bba842 to your computer and use it in GitHub Desktop.
Save Wicowyn/3abdfe1a563e26bba842 to your computer and use it in GitHub Desktop.
To parse twitter message
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
/**
* Created by yapiti on 07/09/15.
*/
public class Main {
public static void main(String[] args) throws IOException {
String text=readFile(args[0], Charset.defaultCharset());
int maxWidth=Integer.parseInt(args[1]);
int pageCount=process(text.length(), maxWidth);
int last=0;
for(int i=1; i<= pageCount; i++) {
StringBuilder stringBuilder=new StringBuilder();
int end=Math.min(last+maxWidth-lengthFor(i, pageCount), text.length());
String subText=text.substring(last, end);
stringBuilder.append(subText);
stringBuilder.append(toString(i, pageCount));
System.out.println(stringBuilder.toString());
last=end;
}
}
private static int process(int lengthText, int max) {
int pageCount=lengthText/max;
int newPageCount= calculPageCount(lengthText, pageCount, max);
while (pageCount != newPageCount) {
pageCount = newPageCount;
newPageCount=calculPageCount(lengthText, pageCount, max);
}
return pageCount;
}
private static int calculPageCount(int lengthText, int pageCount, int max) {
double newPageCount=((double) (lengthText+lengthPaginationFor(pageCount))) / max;
return (int) Math.ceil(newPageCount);
}
private static int lengthPaginationFor(int pageCount) {
int total=0;
for(int i=1; i <= pageCount; i++) {
total+=lengthFor(i, pageCount);
}
return total;
}
private static int lengthFor(int i, int totalPage) {
return toString(i, totalPage).length();
}
private static String toString(int i, int totalPage) {
return " "+Integer.toString(i)+"/"+Integer.toString(totalPage);
}
private static String readFile(String path, Charset encoding) throws IOException {
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, encoding);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment