阅读量:112
在Java中,可以使用String.format()方法和String.repeat()方法来实现类似padleft的功能,处理不同长度的字符串。
- 使用
String.format()方法:
public class PadLeft {
public static void main(String[] args) {
String input = "Java";
int targetLength = 10;
String padded = padLeft(input, targetLength);
System.out.println(padded); // 输出 " Java"
}
public static String padLeft(String input, int targetLength) {
if (input == null || input.length() >= targetLength) {
return input;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < targetLength class="hljs-string">" ");
}
sb.append(input);
return sb.toString();
}
}
- 使用
String.repeat()方法(Java 11及以上版本):
public class PadLeft {
public static void main(String[] args) {
String input = "Java";
int targetLength = 10;
String padded = padLeft(input, targetLength);
System.out.println(padded); // 输出 " Java"
}
public static String padLeft(String input, int targetLength) {
if (input == null || input.length() >= targetLength) {
return input;
}
return String.join("", Collections.nCopies(targetLength - input.length(), " ")) + input;
}
}
这两种方法都可以实现将字符串向左填充至指定长度。你可以根据自己的需求和Java版本选择合适的方法。