gpt4 book ai didi

java - 计算字符串的长度和 "padding"it

转载 作者:行者123 更新时间:2023-11-29 03:29:54 24 4
gpt4 key购买 nike

我正在做一个赋值,它需要一个以字符串和整数作为参数的方法。该方法应该用空格填充参数字符串,直到其长度为给定长度。例如,padString("hello", 8 应该返回"hello___"(_代表三个空格)) 如果int大于字符串的长度,那么它就直接返回字符串。我在获取程序的“填充”部分时遇到问题。

由于这项作业在本书的开头,我认为它可以用 forloops、参数和常用字符串方法等初学者的东西来完成,因为我还不应该使用 if/else 语句。

这是我目前拥有的明显有缺陷的代码:

public class Exercise11 {

public static final String word = "congratulations";
public static final int length = 10;

public static void main(String[] args) {
padString();

}

public static String padString(String word, int length) {
if (word.length() >= length) {
return word.substring(0,length + 1);
} else {
String thing = word;
return word + addSpaces(word, length);
}

}

public static void addSpaces(String word, int length) {
for (int i = 1; i <= length-word.length(); i++) {
return (" ");
}
}

}

顺便问一下,有没有办法用 for 循环将诸如空格之类的东西添加到 String 变量中?感谢您的帮助。

最佳答案

这是一个合理的开始......

padString 需要两个参数,Stringint,所以这...

public static void main(String[] args) {
padString();
}

可以改成...

public static void main(String[] args) {
padString(word, length);
}

下一个问题是您的 addSpaces 方法。循环中的 return 语句意味着循环只会执行一次,并且只会返回一个空格字符。

相反,您需要将每个循环中的空格连接到一个临时的 String,您将把它传回,例如...

public static String addSpaces(String word, int length) {
StringBuilder sb = new StringBuilder(length);
for (int i = 0; i < length - word.length(); i++) {
sb.append(" ");
}
return sb.toString();
}

所以,如果我跑...

System.out.println("[" + padString("hello", length) + "]");

我明白了

[hello     ]

关于java - 计算字符串的长度和 "padding"it,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18822003/

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