split
is not best option here, but you can use Pattern
and Matcher
classes with this regex
\\G.{1,80}(\\s+|$)
which means
\\G
place of last match, or if it is first iteration of searching for match (so there was not any yet) start of the string (represented by ^
)
.{1,80}
any characters can appear between one and eighty times
(\\s+|$)
one or more whitespaces or end of string
You can use it this way
String data = "Welcome to fancy! A text based rpg. Perhaps you could tell us your name brave "
+ "adventurer? ";
Pattern p = Pattern.compile("\\G.{1,80}(\\s+|$)");
Matcher m = p.matcher(data);
while(m.find())
System.out.println(m.group().trim());
Output:
Welcome to fancy! A text based rpg. Perhaps you could tell us your name brave
adventurer?
But assuming that you can face with very long words which shouldn't be split you can add
\\S{80,}
to your regex to also let it find non-whitespace strings which length is 80 or more.
Example:
String data = "Welcome to fancy! A text based rpg. Perhaps you could tell us your name brave "
+ "adventurer? foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar";
Pattern p = Pattern.compile("\\G.{1,80}(\\s+|$)|\\S{80,}");
Matcher m = p.matcher(data);
while (m.find())
System.out.println(m.group().trim());
Output:
Welcome to fancy! A text based rpg. Perhaps you could tell us your name brave
adventurer?
foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar