java - 如何格式化两行字符串,以便底行的项目与java中顶行的项目对齐

标签 java string formatting format

所以我设置了这样的内容:

public static void main(String[] args) {
    String fun = ("3000.05 500 6000.987 70 8000.00");
    String lame = ("3 5 6 7 8");
    String total = (fun + "\n" + lame);
    System.out.println(total);
}

如何格式化整个字符串,以便在打印时打印如下:

3000.05 500 6000.987 70 8000.00  
      3   5        6  7       8

我一直在寻找,但似乎找不到我要找的东西。我只是想将底部字符串的每个部分与顶部字符串的最远部分右对齐。

最佳答案

您可以使用 for 循环遍历字符串上的每个位置并创建一个新字符串来存储您要查找的内容。例如。

public static void main(String[] args) {
String fun = ("3000.05 500 6000.987 70 8000.00");

String newStringToBePrinted="";
for(char c: fun){
 if (!(c == ' '|| c == '.')){
  String ch = c+"";
   newStringToBePrinted+= ch;
} else{
  newStringToBePrinted+="-";
 }
}

String total = (fun + "\n" + newStringToBePrinted);


System.out.println(total);
} 

希望这有帮助。

关于java - 如何格式化两行字符串,以便底行的项目与java中顶行的项目对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36367728/

相关文章:

java - Jelastic 上多应用一个数据库场景的最佳配置

java - 用java中的属性文件的值替换String

c# - String.ToString 有什么合理的用途吗?

java - 使用Spring Boot时如何设置ForkJoinPool的线程工厂?

java - 当我们可以使用 Set 来添加唯一值时,为什么还要使用 ArrayList?

php - 检查数组是否部分匹配 (PHP)

Python - 根据不区分大小写的内容删除字符串的一部分

python - Python 中的 Namedtuple 格式化/ pretty-print

python - 如何使用 Python 仅将 Excel 单元格中字符串的一部分加粗?

javascript - 在 JavaScript 中将十六进制数字格式化为短 UUID