美元符号($)在printf格式字符串中做什么? [英] What does the dollar sign ($) do in a printf format string?

查看:649
本文介绍了美元符号($)在printf格式字符串中做什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用类似于此网页的printf语句在java中进行格式化:点击此处。但我无法弄清楚$ sign的目的是什么。有人可以向我解释一下吗?

I am trying to format in java using the printf statement like in this webpage: Click Here. But I just can't figure out what the purpose of the $ sign is. Can someone please explain this to me?

输入:

java 100
cpp 65
python 50

预期输出:(应该有一个空格而不是_)

Expected Output: ( there should be a space instead of _ )

 ================================
 java___________100 
 cpp___________065 
 python_________050 
 ================================

我的代码:

public class Solution {

    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        System.out.println("================================");
        for(int i=0;i<3;i++)
        {
            String s1=sc.next();
            int x=sc.nextInt();
            System.out.printf(s1 + "%03d", x);
            System.out.println();
        }
        System.out.println("================================");

    }
}


推荐答案

参数索引您可以阅读文档。我将尝试为您解释教程中的字符串:

It is the Argument Index. You can read the docs. I will try to explain the string from the tutorial for you:

String fmt = "%1$4s %2$10s %3$10s%n";

// format
cnsl.printft(fmt, "Items", "Quantity", "Price");
cnsl.printft(fmt, "-----", "-----", "-----");
cnsl.printft(fmt, "Tomato", "1Kg", "15");
cnsl.printft(fmt, "Potato", "5Kg", "50");
cnsl.printft(fmt, "Onion", "2Kg", "30");
cnsl.printft(fmt, "Apple", "4Kg", "80");

通常格式为%[argument_index $] [flags] [width ] [精度]换算

在我们的示例中,#$ 指向 printft()<中的位置声明。我们有3个字符串要格式化,因此我们的格式字符串为 1 $ 2 $ 3 $ 。每个参数之间的宽度后面的数字。此宽度从0开始,这意味着实际宽度为+1。 s 是我们转换为字符串,最后是%n 新行。

In our example, #$ points to the position within our printft() statement. We have 3 strings to be formatted and hence why our format string has 1$, 2$,3$. The number that follows its the width between each argument. This width begins at 0 which means the actual width would be +1. The s is our conversion to string and the %n new line at the end.

Items      Quantity      Price
-----      --------      -----
Tomato     1Kg           15
Potato     5Kg           50
Onion      2Kg           30
Apple      4Kg           80

这篇关于美元符号($)在printf格式字符串中做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆