展开全部
我来试试……
主要使用StringBuilder的replace(start, end, str)方法, 把一个字符串中先填满空格,再计算位置,替换成你要的字符。注意636f70793231313335323631343130323136353331333363386165:这里有个小坑:在新建一个StringBuilder的时候,虽然看上去里面已经填充了字符,但实际上是空的;假如不从头到尾填充空格(" "),在replace()时Java会认为字符串的长度是0,从而出现java.lang.StringIndexOutOfBoundsException: start > length()
最后,sample里面的antidisestablishmentarianistic长达30个字符,而测试数据中给的行长是20,需要考虑(假如字词长度大于输入的20,则需要加长行长)。
最后的代码:(还有一点:题目的import里面包括了java.util.Arrays,但我代码没用,不知道会不会被认为是没有观察题意而判错。也许是我多心了)import java.util.ArrayList;
import java.util.List;
public class Assign1Q2 {
protected static char[] justify(char[] inputText, int lineWidth, char just) {
StringBuffer sb = new StringBuffer("");
List words = new ArrayList();
for (int i=0; i
if (inputText[i] != ' ' && inputText[i] != '\n') {
sb.append(inputText[i]);
} else {
inputText[i] = '\n';
words.add(sb.toString());
sb = new StringBuffer(""); //clear content
}
}
words.add(sb.toString()); //add last word because the last char is not space/'\n'.
for (int i=0; i
if (words.get(i).length() >= lineWidth) {
lineWidth = words.get(i).length();
}
}
char[] output = null;
StringBuilder sb2 = new StringBuilder("");
StringBuilder line = null;
for (String word: words) {
line = new StringBuilder("");
for (int i=0; i
line.append(" ");
}
switch (just) {
case 'l':
line.replace(0, word.length(), word);
break;
case 'r':
line.replace(lineWidth-word.length(), lineWidth, word);
break;
case 'c':
int rest = lineWidth-word.length(); //all the spaces' length
int begin = 0;
if (rest % 2 != 0) {
begin = (int)(rest/2)+1;
} else {
begin = rest/2;
}
line.replace(begin, begin+word.length(), word);
break;
}
line.append('\n');
sb2.append(line);
}
output = sb2.toString().toCharArray();
return output;
}
}
最后效果:The
quick
brown
antidisestablishmentarianistic
fox
jumps
over
the
lazy
dog
The
quick
brown
antidisestablishmentarianistic
fox
jumps
over
the
lazy
dog
The
quick
brown
antidisestablishmentarianistic
fox
jumps
over
the
lazy
dog