Code:
public class Ex7
{
//constructor
public static String s = "1234567890123456789 In the output words on a line are separated by precisely one space verb+' '+,\nlines are separated by\n\nprecisely one newline (so no trailing spaces) and";
public static int width = 20;
public static void format(){
StringBuilder sb = new StringBuilder();
for(int start = 0; start < s.length(); start += width){
int cursor = start + width - 1;
boolean w = true;
while(w){
if(cursor-1 < s.length()){
if((s.charAt(cursor) == ' ') || (s.charAt(cursor)== '\t')){
if(start + width -1 < s.length()){
sb.append(s.substring(start, cursor));
sb.append("\n");
w = false;
}
else{
sb.append("\n");
sb.append(s.substring(start));
w = false;
}
}
else{
cursor--;
}
}
else{
sb.append("\n");
sb.append(s.substring(start));
w = false;
}
}
}
System.out.println(sb);
}
}
Hallo zusammen,
Ziel ist es, einen gegebenen String s per StringBuilder so zu formatieren, dass nach jedem (in diesem Fall) 20. Zeichen ein Zeilenumbruch stattfindet. Es dürfen aber keine Wörter gespalten werden (also falls 20. Zeichen ein Wort, dann Zeilenumbruch vor diesem Wort).
Mein aktueller output:
Code:
1234567890123456789
In the output words
on a line are
ted by precisely
space verb+'
nes are separated
precisely one
ine (so no trailing
spaces) and
Laut Aufgabenstellung sollte der optimale Output folgendermaßen aussehen:
Code:
01234567890123456789
In the output words
on a line are
separated by
precisely one space
\verb+' '+, lines
are separated by
precisely one
newline (so no
trailing spaces)
and
Wir dürfen die Scanner class oder andere third-party Libraries nicht verwenden.
Seht ihr meinen Fehler im Code?
Danke im Vorraus für Eure Antworten.
mfg FLiiX