字符串替换

  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:
相关推荐
恸流失1 分钟前
集合练习1
java
LiLiYuan.1 分钟前
Arrays类和List接口的关联
java·开发语言·windows·python
stay_awake__2 分钟前
Maven+mybatis
java·maven
武子康20 分钟前
Java-170 Neo4j 事务、索引与约束实战:语法、并发陷阱与速修清单
java·开发语言·数据库·sql·nosql·neo4j·索引
q***235723 分钟前
在2023idea中如何创建SpringBoot
java·spring boot·后端
7澄142 分钟前
Java 实战:投票统计系统(HashMap 应用)
java·开发语言·intellij-idea·交互·控制台·hashmap
q***787842 分钟前
SpringBoot后端服务重定向
java·spring boot·后端
Fantasydg1 小时前
外卖项目day02
java
Kuo-Teng1 小时前
LeetCode 139: Word Break
java·算法·leetcode·职场和发展·word·动态规划