美元符号($)在printf格式字符串中做什么?

编程入门 行业动态 更新时间:2024-10-25 06:28:59
本文介绍了美元符号($)在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格式字符串中做什么?

本文发布于:2023-10-22 22:25:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1518908.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   中做   符号   美元   格式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!