[英]Java equivalent to C# $“{var}” formatting
So I am learning a bit of Java and I'm just curios if there is an equivalent to the string format with the $ sign like in C#.所以我正在学习一些Java,如果有与C#中的$符号等价的字符串格式,我只是好奇。 For example
例如
string s = $"Date: {DateTime.Now}";
// s = Date: 5/27/2020 8:02:25 AM
Is this possible in Java?这在 Java 中是否可行? I find it more convenient than doing it with indexes.
我发现它比使用索引更方便。
Java provides a type-safe way of concatenating Strings. Java 提供了一种连接字符串的类型安全方式。
Here is a demonstration using jshell:这是一个使用 jshell 的演示:
> jshell
jshell> import java.time.*;
jshell> String s = ("Date: " + LocalDateTime.now());
s ==> "Date: 2020-05-27T09:49:10.476140"
jshell>
Here is a working example program that uses Date formatting:这是一个使用日期格式的工作示例程序:
// File name: Demo.java
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Demo {
public static void main(String[] args) {
Format f = new SimpleDateFormat("dd/mm/yyyy hh:mm:ss a");
String s = ( "Date: " + f.format(new Date()) );
System.out.println(s);
}
}
Output: Output:
> javac Demo.java
> java Demo
Date: 27/03/2020 10:03:02 am
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.