字符串替换

  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:
相关推荐
Seven978 分钟前
【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
java·后端·设计模式
matrixlzp11 分钟前
Java 生成图形验证码
java·spring
冰淇淋@12 分钟前
HTTP发送POST请求的两种方式
java·spring boot·http
codingPower27 分钟前
IDEA接入阿里云百炼中免费的通义千问[2025版]
java·阿里云·intellij-idea
JouJz1 小时前
Java基础系列:深入解析反射机制与代理模式及避坑指南
java·开发语言·代理模式
小安同学iter1 小时前
Spring(七)AOP-代理模式
java·后端·spring
鸽鸽程序猿1 小时前
【JavaEE】SpringIoC与SpringDI
java·开发语言·java-ee
Yuanymoon2 小时前
【由技及道】API契约的量子纠缠术:响应封装的十一维通信协议【人工智障AI2077的开发日志012】
java·架构设计·spirng
lucky1_1star2 小时前
FX-函数重载、重写(覆盖)、隐藏
java·c++·算法
李长渊哦3 小时前
学习文章:Spring Boot 中如何使用 `@Async` 实现异步处理
java·spring boot·学习