println转换格式输出字符串
时间: 2023-07-01 18:19:09 浏览: 75
要用到格式化字符串,可以使用String.format()方法。例如:
```
int num = 10;
String str = "hello";
System.out.println(String.format("%d %s", num, str));
```
输出结果为:
```
10 hello
```
其中,`%d`表示输出整数,`%s`表示输出字符串。`%d`和`%s`分别对应后面的参数`num`和`str`。可以根据需要使用不同的格式占位符。
相关问题
LocalDateTime 转换字符串 时间格式化
你可以使用DateTimeFormatter类来格式化LocalDateTime对象为字符串。以下是一个示例代码:
```java
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedDateTime = now.format(formatter);
System.out.println("Formatted DateTime: " + formattedDateTime);
}
}
```
这里,我们使用`ofPattern`方法创建了一个指定格式的DateTimeFormatter对象,然后使用`format`方法将LocalDateTime对象转换为字符串。
你可以根据需要自定义日期和时间的格式。在示例中,我们使用了"yyyy-MM-dd HH:mm:ss"的格式。这代表年份(四位数)、月份、日期、小时(24小时制)、分钟和秒。
执行上述代码将输出当前的LocalDateTime对象的格式化字符串。
java转换字符串编码格式
可以使用Java的String类提供的getBytes()方法将字符串编码为指定格式的字节数组。示例代码如下:
```java
String s = "你好,世界!";
byte[] s_utf8 = s.getBytes("UTF-8");
System.out.println(Arrays.toString(s_utf8));
```
输出结果为:
```
[-28, -67, -96, -27, -91, -67, 44, -27, -113, -103, -25, -107, -117, 33]
```
其中,每个负数代表一个字节,这些字节就是字符串被编码为utf-8格式的结果。需要注意的是,在getBytes()方法中,需要传入的参数是目标编码格式的名称,如"UTF-8"、"GBK"等。如果不指定编码格式,则会使用默认的编码格式,可能会导致编码错误。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)