Skip to content

Instantly share code, notes, and snippets.

@SMontiel
Last active April 6, 2020 23:54
Show Gist options
  • Save SMontiel/ac041c3efdc4ec808be30d036ac45869 to your computer and use it in GitHub Desktop.
Save SMontiel/ac041c3efdc4ec808be30d036ac45869 to your computer and use it in GitHub Desktop.
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
String input = "the quick brown fox jumps over the lazy dog\n" +
"Mi nombre es Salvador Montiel";
String input2 = "the quick brownred fox jumps over the lazy dog\n";
wordWrapping(input, 15).forEach(line -> {
System.out.println("Line " + line.number + ": " + line.rawLine);
line.chunks.forEach(chunk -> System.out.println("> " + chunk));
});
System.out.println("------------------------------------------------------------------------------------");
wordWrapping(input2, 15).forEach(line -> {
System.out.println("Line " + line.number + ": " + line.rawLine);
line.chunks.forEach(chunk -> System.out.println("> " + chunk));
});
}
public static List<Line> wordWrapping(String inputText, int length) {
String[] lines = inputText.split("\n");
List<Line> list = new ArrayList<>();
int counter = 0;
for (String line : lines) {
int len = line.length();
if (len > length) {
List<String> chunks = getChunksFromLine(line, length);
list.add(new Line(line, chunks, counter + 1));
} else {
list.add(new Line(line, new ArrayList<>(), counter + 1));
}
counter++;
}
return list;
}
private static List<String> getChunksFromLine(String line, int numChars) {
List<String> list = new ArrayList<>();
String[] words = line.split(" ");
StringBuilder str = new StringBuilder();
int counter = 0;
for (String a : words) {
// Number one represents the whitespace between str and a
if (str.length() + 1 + a.length() <= numChars) {
str.append(counter > 0 ? " " : "").append(a);
} else if (str.length() <= numChars) {
list.add(str.toString());
str = new StringBuilder(a);
}
if (counter == words.length - 1) {
list.add(str.toString());
}
counter++;
}
return list;
}
public static class Line {
public final String rawLine;
public final List<String> chunks;
public final int number;
public Line(String rawLine, List<String> chunks, int number) {
this.rawLine = rawLine;
this.chunks = chunks;
this.number = number;
}
@Override
public String toString() {
return "Line{" +
"rawLine='" + rawLine + '\'' +
", chunks=" + chunks +
", number=" + number +
'}';
}
}
private static List<String> _getChunksFrom(String item, int numChars) {
String temp = item;
List<String> list = new ArrayList<>();
while (temp.length() >= numChars) {
list.add(temp.substring(0, numChars));
temp = temp.substring(numChars);
}
if (temp.length() > 0) list.add(temp);
return list;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment