2

Java自带的4种字符串组织和格式化方法

 9 months ago
source link: https://blog.didispace.com/java-string-compose-and-format/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Java自带的4种字符串组织和格式化方法

在Java中,组织字符串是平时最常见的操作,这里总结一下Java自带的四种处理方式。

1. 使用+拼接

String name = "DD";
String host = "blog.didispace.com";
String result = "hello " + name + ", your blog is " + host;

这种方法很容易上手,甚至可以混合使用非字符串值来一起组织。然而,结果代码编写起来非常不易阅读和维护。最大的缺点是每次我们使用+运算符时都会分配一个新的字符串。所以,JDK中还提供了多种优化策略来减少字符串的创建,比如下面的方案2。在工作中,要尽量避免使用方案1,而是下面的方案。

2. 使用StringBufferSpringBuilder

String name = "DD";
String host = "blog.didispace.com";
String result = new StringBuilder()
.append("hello ")
.append(name)
.append(", your blog is ")
.append(host)
.toString();

StringBufferStringBuilder是专门用于字符串连接的实现类,它们都提供了用于插入、替换和查找字符串的方法。但它们之间还有一定区别,StringBuffer是线程安全的,而StringBuilder则不是,所以在使用的时候要注意场景。

3. 使用String::format and String::formatted

String name = "DD";
String host = "blog.didispace.com";
String template = "hello %s, your blog is %s";
String result = format.formatter(name, host);

String类本身也提供了一些格式化方法,比如:

  • static String format(String format, Object... args)
  • static String format(Locale locale, String format, Object... args)
  • String formatted(Object... args) (Java 15+)

这些方法是以模版的方式来实现字符串的拼接,可以有效地节省字符串创建的数量。

4. 使用java.text.MessageFormat

String name = "DD";
String host = "blog.didispace.com";
String result = MessageFormat.format("hello {0}, your blog is {1}", name, host);

MessageFormat类型与上面String本身自带的format有点类似,但语法风格上有很大的差别。MessageFormat的参数风格有点像slf4j,而String自带的format风格更像C语言中的print。

除了这些JDK自带的方案之外,还有很多开发者自己封装的处理方法,后面再总结一些优秀的封装,感兴趣的记得关注下程序猿DD或者收藏我的博客。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK