2

I am attempting to split a sentence that is being printed to the console in order to avoid cut offs like so @ 80 chars:

Welcome to fancy! A text based rpg. Perhaps you could tell us your name brave ad
venturer?

So I would like it to print like so

Welcome to fancy! A text based rpg. Perhaps you could tell us your name brave 
adventurer?

Is there a way to do this with String.split() ?

infamoustrey
  • 730
  • 8
  • 16

3 Answers3

0

Depending on how exact it has to be, Regex can do this pretty well. If you just need to split at spaces, a simple

String eg = "Example sentence with, some. spaces! and stuff";
String[] splitSentence = eg.split(" ");

will do the job, splitting the string at every space and thus returning the words with their adjacent special characters as a String array. You could then simply add up the characters (with the spaces inbetween) and if you pass your border (in your case 80), pop the last word and add a '\n':

String getConsoleFormattedString(String s, int rowLength) {
  String[] split = s.split(" ");
  String ret = "";
  int counter = 0,

  for(int i = 0; i < split.length; i++) {
    if(counter + split[i] + 1 <= 80)
      ret += split[i] + " ";
    else {
      ret += "\n";
      counter = 0;
      i--;
    }
  }

  return ret;
}

I will let you figure out how to handle words with > 80 letters, for the sake of simplicity

LionC
  • 3,106
  • 1
  • 22
  • 31
0

You can do something like this, where you decide whether to do a new line or not, depending on the lines current size:

public static String getLines(String line){

    String[] words = line.split(" ");
    StringBuilder str = new StringBuilder();
    int size = 0;
    for (int i = 0; i < words.length; i++) {
        if(size==0){
            str.append(words[i]);
        }
        if(size+words[i].length()+1<=80){
            str.append(" ").append(words[i]);
            size++;
        }else{
            str.append("\n").append(words[i]);
            size = 0;
        }
        size+=words[i].length();
    }
    return str.toString();
}

Another different way of doing the same:

public static String getLines2(String line){
    StringBuilder str = new StringBuilder();
    int begin = 0;

    while(begin<line.length()){
        int lineEnd = Math.min(begin + 80, line.length());
        while(lineEnd<line.length()&&line.charAt(lineEnd)!= ' '){
            lineEnd--;
        }
        str.append(line.subSequence(begin, lineEnd));
        if(lineEnd<line.length()) str.append("\n");
        begin = lineEnd+1;
    }
    return str.toString();
}
magodiez
  • 741
  • 2
  • 10
  • 23
0

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
Pshemo
  • 122,468
  • 25
  • 185
  • 269