gpt4 book ai didi

java - 通过添加空格使字符串大小相等

转载 作者:行者123 更新时间:2023-11-29 05:05:45 25 4
gpt4 key购买 nike

我有一个字符串列表。我想让所有的字符串长度相等。到目前为止我尝试过的是

    int largestLineLength = 0;

for(int i=0;i<list.size();i++){
String s = list.get(i);
list.remove(s)
list.add(s.trim());
}
//get the largest line
for (String s : list) {
int length = s.trim().length();
if (length > largestLineLength) {
largestLineLength = length;
}
}

for(String s: list){
while(s.length() != largestLineLength){
//add spaces to s
}
}

要求:

  1. 通过添加空格使所有行等长字里行间。
  2. 该行前后不得添加空格。
  3. 空格应均匀分布,使所有行均等

例如

Luke Skywalker has returned 
to his home planet of Tatooine
in order to — okay, you
know what, we don't care.
We were thinking of not even
doing this one.

应该是

Luke  Skywalker  has  returned 
to his home planet of Tatooine
in order to — okay, you
know what, we don't care.
We were thinking of not even
doing this one.

附言最后一行是个异常(exception)

最佳答案

一个简单的解决方案是找出最长行和当前行之间的差异。并找出你所在行中的每个单词,然后在每个世界之后分配你的空间。

我已经实现了这个解决方案,并且可以在线获得here看看我的解决方案:

public static void main(String[] args) {
List<String> list = new ArrayList<String>();

list.add("Luke Skywalker has returned");
list.add("to his home planet of Tatooine");
list.add("in order to — okay, you");
list.add("know what, we don't care.");
list.add("We were thinking of not even");
list.add("doing this one.");

int largestLineLength = 0;

for (String s : list) {
int length = s.length();
if (length > largestLineLength) {
largestLineLength = length;
}
}

List<String> outputs = new ArrayList<String>();

for (String s : list.subList(0, list.size() - 1)) {

int needSpace = largestLineLength - s.length();
if (needSpace > 0) { //check if we need space in this line.
String[] words = s.split(" "); //find words in the line
int index = 0;

StringBuilder[] stringBuilders = new StringBuilder[words.length];

for (int i = 0; i < words.length - 1; i++) {
stringBuilders[i] = new StringBuilder(words[i]);
stringBuilders[i].append(" ");
}

stringBuilders[words.length - 1] = new StringBuilder(words[words.length - 1]);

while (needSpace > 0) { //add spaces and decrease needSpace until it reaches zero.
stringBuilders[index].append(" "); //add space to the end of every world in order
index = index == words.length - 2 ? 0 : index + 1; //words-2 is because we didnt want any spaces after last word of line.
needSpace--;
}

StringBuilder stringBuilder = new StringBuilder();

for (int i = 0; i < words.length; i++) {
stringBuilder.append(stringBuilders[i]);
}


s = stringBuilder.toString();
}
outputs.add(s);
}
outputs.add(list.get(list.size()-1));

for(String s : outputs){
System.out.println(s);
}
}

Luke  Skywalker  has  returned
to his home planet of Tatooine
in order to — okay, you
know what, we don't care.
We were thinking of not even
doing this one.

关于java - 通过添加空格使字符串大小相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30412238/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com