字符串替换

  1. String.format("hello %s", "1234");

转换符 说明 参数示例
%s 字符串 "1234"
%c 类型字符 'a'
%b 布尔类型 true/false
%d 整数,十进制 10
%x 整数,十六进制 0x12
%o 整数,八进制 012
%f 浮点类型 0.12f
%e 指数
%g 通用浮点数
%h 散列
%% 百分比
%n 换行
%tx 日期与时间类型(x代表不同的日期与时间转换符)
  1. 实际使用时,%s,%d,%f,这三个足以应付大部分场景

  2. %s的占位标记,传参如果不是String类型,那么实际替换的是arg.toString(),所以数组会输出地址,list输出内容

  3. %d传入整数,如果传参不是整数,就会抛出异常:java.util.IllegalFormatConversionException

  4. 传入参数个数不匹配

    1. String.format("hello %s %s", "123")模板要求两个参数,实际只传入一个参数,会直接抛异常MissingFormatArgumentException
    2. 参数过多:String.format("hello %s", "123", "456");执行正常,多余的参数不会被替换
  5. 一个参数,需要替换模板中多个占位的场景:MessageFormat

    java 复制代码
    String ans = MessageFormat.format("hello {0}, with site {0}{1}","123","345")
    1. 使用{数字}来表示占位,其中数字对应的是传参的下标,因此当一个参数需要复用时,使用MessageFormat比较简单

    java 复制代码
    System.out.println(MessageFormat.format("hello }", 123));
    System.out.println(MessageFormat.format("hello { world", 456));
    第一个是没有问题的,第二个会抛出异常java.lang.
    IllegalArgumentException: Unmatched braces in the pattern.
    1. 如果字符串中希望输出{,可以使用单引号处理:System.out.println(MessageFormat.format("hello '{' world", 456));

    2. 单引号

      1. 在字符串模板中,如果有单引号,需要使用两个单引号,只有一个单引号,会导致后面所有的占位不生效

      java 复制代码
      System.out.println(MessageFormat.format("hello {0}, I'm {1}", "123", "555"));
      会输出 : hello 123, Im {1}
      
      使用两个单引号
      System.out.println(MessageFormat.format("hello {0}, I''m {1}", "123", "555"));
      输出:hello 123, I'm 555
    3. 序号

      1. 要求在{}中指定参数的序号,如果模板中没有指定会直接报异常
      2. System.out.println(messageFormat.format("hello {}, world", "1111"));
      3. java.lang.IllegalArgumentException: can't parse argument number:
相关推荐
JH30735 小时前
SpringBoot 优雅处理金额格式化:拦截器+自定义注解方案
java·spring boot·spring
Coder_Boy_6 小时前
技术让开发更轻松的底层矛盾
java·大数据·数据库·人工智能·深度学习
invicinble6 小时前
对tomcat的提供的功能与底层拓扑结构与实现机制的理解
java·tomcat
较真的菜鸟6 小时前
使用ASM和agent监控属性变化
java
黎雁·泠崖6 小时前
【魔法森林冒险】5/14 Allen类(三):任务进度与状态管理
java·开发语言
qq_12498707538 小时前
基于SSM的动物保护系统的设计与实现(源码+论文+部署+安装)
java·数据库·spring boot·毕业设计·ssm·计算机毕业设计
Coder_Boy_8 小时前
基于SpringAI的在线考试系统-考试系统开发流程案例
java·数据库·人工智能·spring boot·后端
Mr_sun.8 小时前
Day06——权限认证-项目集成
java
瑶山8 小时前
Spring Cloud微服务搭建四、集成RocketMQ消息队列
java·spring cloud·微服务·rocketmq·dashboard
abluckyboy8 小时前
Java 实现求 n 的 n^n 次方的最后一位数字
java·python·算法