Java占位符

本文对比了Java中四种字符串拼接方法的性能:使用+、StringBuilder、String.format和MessageFormat.format。实验结果显示,使用+和StringBuilder的效率最高,MessageFormat效率次之,String.format效率最低。文章还详细解析了String.format和MessageFormat.format的占位符格式。

 

一、背景

  在使用java开发的过程中,经常需要使用将字符串拼接到一起(比如,用于日志输出),常用方法如下:

  1. 使用+将不同字符串进行拼接
  2. 使用StringBuilder
  3. 使用String.format
  4. 使用MessageFormat.format

 

二、4种方式性能对比

  上面4中方式,性能方面孰优孰劣,可以做如下验证:

    public static void main(String[] args) throws Exception {
        long start = System.currentTimeMillis();
        int count = 1000000;
        for (int i = 0; i < count; i++) {
            String s = "Hi " + i + "; Hi to you " + i * 2;
        }
        long end = System.currentTimeMillis();
        System.out.println("Concatenation = " + ((end - start)) + " millisecond");
        start = System.currentTimeMillis();
        for (int i = 0; i < count; i++) {
            String s = String.format("Hi %s; Hi to you %s", i, +i * 2);
        }
        end = System.currentTimeMillis();
        System.out.println("Format = " + ((end - start)) + " millisecond");
        start = System.currentTimeMillis();
        for (int i = 0; i < count; i++) {
            String s = MessageFormat.format("Hi %s; Hi to you %s", i, +i * 2);
        }
        end = System.currentTimeMillis();
        System.out.println("MessageFormat = " + ((end - start)) + " millisecond");
        start = System.currentTimeMillis();
        for (int i = 0; i < count; i++) {
            StringBuilder bldString = new StringBuilder("Hi ");
            bldString.append(i).append("; Hi to you ").append(i * 2).toString();
        }
        end = System.currentTimeMillis();
        System.out.println("StringBuilder = " + ((end - start)) + " millisecond");
    }

 

  得到结果如下:

Concatenation = 141 millisecond
Format = 1880 millisecond
MessageFormat = 383 millisecond
StringBuilder = 142 millisecond

 

  将count的值增加10倍,到10000000,得到结果如下:

Concatenation = 1379 millisecond
Format = 18944 millisecond
MessageFormat = 3690 millisecond
StringBuilder = 1487 millisecond

 

  从上面的实验中可以得到如下结论

  1、使用+和StringBuilder效率最高;MessageFormat效率次之,大约相当于前面两种方式的3倍左右;String.format效率最差,差出10倍不止。

  

三、占位符

  后两种方式需要使用占位符,而且使用的占位符格式不相同。

  1、String.format

    解析占位符的方式为正则表达式,使用占位符格式为:%1$s,%2$s。

  占位符完整格式为: %[index$][标识]*[最小宽度][.精度]转换符 。

  针对不同数据类型的格式化,占位符的格式将有所裁剪。

  % ,占位符的其实字符,若要在占位符内部使用%,则需要写成 %% 。

  [index$] ,位置索引从1开始计算,用于指定对索引相应的实参进行格式化并替换掉该占位符。

  [标识] ,用于增强格式化能力,可同时使用多个 [标识] ,但某些标识是不能同时使用的。

  [最小宽度] ,用于设置格式化后的字符串最小长度,若使用 [最小宽度] 而无设置 [标识] ,那么当字符串长度小于最小宽度时,则以左边补空格的方式凑够最小宽度。

  [.精度] ,对于浮点数类型格式化使用,设置保留小数点后多少位。

  转换符 ,用于指定格式化的样式,和限制对应入参的数据类型。

 

  

  2、MessageFormat.format

    解析占位符的方式为逐字符扫描,找到大括号做标记,使用占位符格式为:{0},{1}

 

 

参考:

  Java魔法堂:String.format详解

  MessageFormat vs String plus性能对比

 

转载于:https://www.cnblogs.com/huanyou/p/9652613.html

### Java 占位符使用方法 在 Java 中,占位符可以通过多种方式实现,常见的有 `String.format()` 方法、`MessageFormat` 类以及正则表达式替换等方式。 #### 1. 使用 `String.format()` 实现占位符 `String.format()` 是一种非常灵活的方式,支持格式化字符串并插入变量。它允许通过 `%` 符号指定占位符的位置和数据类型[^4]。 以下是具体的例子: ```java public class FormatExample { public static void main(String[] args) { String format = "%1$-25s%2$-48s"; System.out.format(format, "姓名", "张三"); // 输出带数字的例子 int age = 23; String message = "我今年%d岁了"; System.out.println(String.format(message, age)); } } ``` 在这个例子中,`%d` 表示整数类型的占位符,而 `-25s` 和 `-48s` 则表示字符串宽度的调整。 --- #### 2. 使用 `MessageFormat` 处理复杂占位符 `MessageFormat` 提供了一种更强大的机制来处理复杂的占位符需求,尤其适合国际化场景下的动态文本生成[^1]。 以下是一个简单的实例: ```java import java.text.MessageFormat; public class MessageFormatExample { public static void main(String[] args) { String message = "oh,{0} is a pig."; Object[] array = {"ZhangSan"}; String value = MessageFormat.format(message, array); System.out.println(value); // 如果需要显示右大括号 '}',可以转义为 '}}' String specialMessage = "oh,}} is a pig."; Object[] specialArray = {}; String specialValue = MessageFormat.format(specialMessage, specialArray); System.out.println(specialValue); } } ``` 这里展示了如何通过 `{}` 来定义占位符,并传递数组作为实际值填充到模板中[^2]。 --- #### 3. 自定义占位符解析器 对于更加自定义化的占位符需求,可以借助正则表达式手动完成匹配与替换操作[^3]。 下面展示了一个基于正则表达式的解决方案: ```java import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; public class CustomPlaceholderExample { public static void main(String[] args) { Map<String, String> map = new HashMap<>(); map.put("title", "标题"); map.put("content", "神舟飞船发射成功"); String template = "{title},您有一条新消息,{content}. {title}"; String result = replaceByMap(template, map); System.out.println(result); } public static String replaceByMap(String content, Map<String, String> params) { String regex = "\\{(\\w+)\\}"; Matcher matcher = Pattern.compile(regex).matcher(content); while (matcher.find()) { String placeholder = matcher.group(); String key = placeholder.substring(1, placeholder.length() - 1); if (params.containsKey(key)) { content = content.replace(placeholder, params.get(key)); } } return content; } } ``` 此代码片段实现了对任意键值对形式的占位符进行替换的功能。 --- #### 4. Android 资源文件中的占位符 在 Android 开发中,`string.xml` 文件也广泛使用占位符技术。开发者可以在 XML 配置中预设好模板,在运行时动态注入所需的数据[^5]。 例如: ```xml <string name="welcome_message">欢迎回来,%1$s!</string> ``` 调用时只需提供相应参数即可完成替换: ```java String welcomeTemplate = getString(R.string.welcome_message); String finalMessage = String.format(welcomeTemplate, "Alice"); System.out.println(finalMessage); // 输出:欢迎回来,Alice! ``` --- ### 总结 Java占位符功能强大且多样,可以根据具体应用场景选择合适的方法。无论是基础的 `String.format()`,还是高级别的 `MessageFormat` 或者完全定制化的正则方案,都能满足不同的开发需求。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值