活跃农民
- 积分
- 814
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2014-3-17
- 最后登录
- 1970-1-1
|
用StringBuilder实现了recursive和非recursive两种版本,欢迎讨论
- import java.util.*;
- import java.util.stream.*;
- class Formatter {
- private static boolean keyStart(int next, char[] str) {
- return next + 2 < str.length && str[next] == '{' && Character.isDigit(str[next + 1]);
- }
- public static String format(String pattern, String ... argu) {
- StringBuilder sb = new StringBuilder();
- List<String> args = Stream.of(argu).collect(Collectors.toList());
- int next = 0;
- char[] str = pattern.toCharArray();
- // invariant: sb contains formatted str[0:next]
- while (next < str.length) {
- if (!keyStart(next, str)) {
- sb.append(str[next++]);
- continue;
- }
- // str[next] == '{'
- int numStart = ++next;
- while (next < str.length && str[next] != '}') {
- ++next;
- }
- if (next == str.length) {
- // reach the pattern end without enclosing '}'
- sb.append(pattern.substring(numStart - 1, next));
- continue;
- }
- // str[next] == '}'
- try {
- int key = Integer.parseInt(pattern.substring(numStart, next));
- String value = args.get(key);
- sb.append(value);
- ++next; // jump out '}'
- } catch (Exception e) {
- sb.append(pattern.substring(numStart - 1, next));
- }
- }
- return sb.toString();
- }
- // keep formatting until reaching a fixed point
- public static String recursiveFormat(String pattern, String ... argu) {
- String formatted = Formatter.format(pattern, argu);
- if (formatted.equals(pattern)) {
- return pattern;
- }
- return recursiveFormat(formatted, argu);
- }
- }
- class Test {
- public static void main(String[] args) {
- System.out.println(Formatter.format(
- "so{0} thi{1} just {2}like {3} this",
- "me", "ng", "", "♂")); // some thing just like ♂this
- System.out.println(Formatter.format("a{0}{0}", "s"));
- System.out.println(Formatter.format("a{0}{0}", "s"));
- System.out.println(Formatter.recursiveFormat("a{{0}{0}}", "0")); // a{{0}{0}} -> a{0} -> a0
- //Formatter.format("a{0}", "s");
- }
- }
复制代码 |
|