Skip to content

Instantly share code, notes, and snippets.

@simolus3
Last active August 29, 2015 14:18
Show Gist options
  • Save simolus3/4d94d1d33a5e61000d0a to your computer and use it in GitHub Desktop.
Save simolus3/4d94d1d33a5e61000d0a to your computer and use it in GitHub Desktop.
Util to create small lines from a string. Useful when having to create item lores.
public static List<String> itemLoreFriendly(String text) {
final int maximumCharsPerLine = 50;
final char space = ' ';
final char newLine = '\n';
List<String> lines = new ArrayList<String>();
while (text.length() > maximumCharsPerLine) {
StringCharacterIterator it = new StringCharacterIterator(text);
//Find the last location of a space befor the character limit.
int lastSpace = -1;
char current = ' ';
while ((current = it.next()) != CharacterIterator.DONE) {
if (it.getIndex() > maximumCharsPerLine) {
break;
}
if (current == space || current == newLine)
lastSpace = it.getIndex();
if (current == newLine)
break; //Force a new line.
}
String line = "";
if (lastSpace > 0) {
line = text.substring(0, lastSpace - 1); //Exclude the last space
} else {
line = text.substring(0, maximumCharsPerLine);
}
text = text.substring(line.length()); //Cut it of from the beginning
lines.add(line);
}
if (text.length() > 0) //Append the rest
lines.add(text);
return lines;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment