字符串替换

  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:
相关推荐
聆风吟º4 分钟前
【Spring Boot 报错已解决】Error creating bean with entityManagerFactory 原因分析与解决方案
java·spring boot·后端
Unstoppable225 分钟前
八股训练营第 34 天 | synchronized 和 Lock 的区别是什么?synchronized 和 ReentrantLock 的区别是什么?
java·八股
r***934811 分钟前
【JavaEE】Spring Boot 项目创建
java·spring boot·java-ee
VX:Fegn089513 分钟前
计算机毕业设计|基于springboot + vue毕业设计选题管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·课程设计
matthew13 分钟前
发布对象和对象逃逸
java
9***g68714 分钟前
SpringSecurity之跨域
java
程序员鱼皮15 分钟前
MySQL 从入门到删库跑路,保姆级教程!
java·计算机·程序员·编程·编程经验
h***673717 分钟前
springboot设置多环境配置文件
java·spring boot·后端
VX:Fegn089518 分钟前
计算机毕设|基springboot+Vue的校园打印系统设计与实现
java·前端·javascript·vue.js·spring boot·后端·课程设计
7ioik19 分钟前
新增的类以及常用的方法有哪些?
java·开发语言·python