Last active
December 25, 2015 23:19
-
-
Save DomWilliams0/7056568 to your computer and use it in GitHub Desktop.
Convert a String into a List, which can be printed continually to scroll the text along.
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
/* | |
Example: | |
--- | |
List<String> scrolling = scroll("This is a scrolling string!", 10, 5); | |
int i = 0; | |
while (true) | |
{ | |
System.out.println(scrolling.get(i++ % scrolling.size())); | |
// some delay | |
} | |
--- | |
Your output would look as if this string was scrolling by: | |
"This is a scrolling string! This is a scrolling string! This is a scrolling string! ...etc" | |
in chunks of 10: | |
"This is a " | |
"his is a s" | |
"is is a sc" | |
... etc | |
*/ | |
/** | |
* @param string The string to scroll | |
* @param width The width of the scroll window | |
* @param spaceBetween The gap between each repetition | |
* @return A List of strings to iterate through continually | |
*/ | |
public static List<String> scroll(String string, int width, int spaceBetween) | |
{ | |
List<String> list = new ArrayList<String>(); | |
// Validation | |
// String is too short for window | |
if (string.length() < width) | |
{ | |
StringBuilder sb = new StringBuilder(string); | |
while (sb.length() < width) | |
sb.append(" "); | |
string = sb.toString(); | |
} | |
// Invalid width/space size | |
if (width < 1) | |
width = 1; | |
if (spaceBetween < 0) | |
spaceBetween = 0; | |
// Add substrings | |
for (int i = 0; i < string.length() - width; i++) | |
list.add(string.substring(i, i + width)); | |
// Add space between repeats | |
StringBuilder space = new StringBuilder(); | |
for (int i = 0; i < spaceBetween; ++i) | |
{ | |
list.add(string.substring(string.length() - width + (i > width ? width : i), string.length()) + space); | |
if (space.length() < width) | |
space.append(" "); | |
} | |
// Wrap | |
for (int i = 0; i < width - spaceBetween; ++i) | |
list.add(string.substring(string.length() - width + spaceBetween + i, string.length()) + space + string.substring(0, i)); | |
// Join up | |
for (int i = 0; i < spaceBetween; i++) | |
{ | |
if (i > space.length()) | |
break; | |
list.add(space.substring(0, space.length() - i) + string.substring(0, width - (spaceBetween > width ? width : spaceBetween) + i)); | |
} | |
return list; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment