字符串替换

  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:
相关推荐
没有bug.的程序员1 小时前
服务安全:内部服务如何防止“裸奔”?
java·网络安全·云原生安全·服务安全·零信任架构·微服务安全·内部鉴权
一线大码1 小时前
SpringBoot 3 和 4 的版本新特性和升级要点
java·spring boot·后端
weixin_440730502 小时前
java数组整理笔记
java·开发语言·笔记
weixin_425023002 小时前
Spring Boot 实用核心技巧汇总:日期格式化、线程管控、MCP服务、AOP进阶等
java·spring boot·后端
一线大码2 小时前
Java 8-25 各个版本新特性总结
java·后端
2501_906150562 小时前
私有部署问卷系统操作实战记录-DWSurvey
java·运维·服务器·spring·开源
better_liang2 小时前
每日Java面试场景题知识点之-TCP/IP协议栈与Socket编程
java·tcp/ip·计算机网络·网络编程·socket·面试题
niucloud-admin3 小时前
java服务端——controller控制器
java·开发语言
To Be Clean Coder3 小时前
【Spring源码】通过 Bean 工厂获取 Bean 的过程
java·后端·spring
Fortunate Chen3 小时前
类与对象(下)
java·javascript·jvm