Java占位符替换工具类

import java.util.HashMap;  
    import java.util.Map;  
      
    import org.slf4j.Logger;  
    import org.slf4j.LoggerFactory;  
      
    /** 
     * 配置文件或模板中的占位符替换工具类 
     * Date: 15-5-8 
     * Time: 下午4:12 
     */  
    public class PlaceholderUtils {  
      
        private static final Logger logger = LoggerFactory.getLogger(PlaceholderUtils.class);  
      
        /** 
         * Prefix for system property placeholders: "${" 
         */  
        public static final String PLACEHOLDER_PREFIX = "${";  
        /** 
         * Suffix for system property placeholders: "}" 
         */  
        public static final String PLACEHOLDER_SUFFIX = "}";  
      
        public static String resolvePlaceholders(String text, Map<String, String> parameter) {  
            if (parameter == null || parameter.isEmpty()) {  
                return text;  
            }  
            StringBuffer buf = new StringBuffer(text);  
            int startIndex = buf.indexOf(PLACEHOLDER_PREFIX);  
            while (startIndex != -1) {  
                int endIndex = buf.indexOf(PLACEHOLDER_SUFFIX, startIndex + PLACEHOLDER_PREFIX.length());  
                if (endIndex != -1) {  
                    String placeholder = buf.substring(startIndex + PLACEHOLDER_PREFIX.length(), endIndex);  
                    int nextIndex = endIndex + PLACEHOLDER_SUFFIX.length();  
                    try {  
                        String propVal = parameter.get(placeholder);  
                        if (propVal != null) {  
                            buf.replace(startIndex, endIndex + PLACEHOLDER_SUFFIX.length(), propVal);  
                            nextIndex = startIndex + propVal.length();  
                        } else {  
                            logger.warn("Could not resolve placeholder '" + placeholder + "' in [" + text + "] ");  
                        }  
                    } catch (Exception ex) {  
                        logger.warn("Could not resolve placeholder '" + placeholder + "' in [" + text + "]: " + ex);  
                    }  
                    startIndex = buf.indexOf(PLACEHOLDER_PREFIX, nextIndex);  
                } else {  
                    startIndex = -1;  
                }  
            }  
            return buf.toString();  
        }  
          
        public static void main(String[] args) {  
            String aa= "我们都是好孩子,${num}说是嘛? 我觉得${people}是傻蛋!";  
            Map<String, String> map = new HashMap<String, String>();  
            map.put("num","小二比");  
            map.put("people","小明");  
            System.out.println(PlaceholderUtils.resolvePlaceholders(aa, map));  
        }  
      
    }  

  

### 编程中的字符串占位符替换 在多种编程语言中,处理字符串占位符替换是一个常见的需求。下面将以 Python 和 Java 为例展示实现方法。 #### Python 中的字符串格式化 Python 提供了几种不同的方式来进行字符串格式化: - **使用 `%` 运算符** 这种方式类似于 C 风格的 printf 函数[^1]。 ```python name = "Alice" age = 30 formatted_string = "Name: %s, Age: %d" % (name, age) print(formatted_string) ``` - **使用 `str.format()` 方法** 这种方法更加灵活并支持位置参数和关键字参数。 ```python formatted_string = "Name: {}, Age: {}".format(name, age) print(formatted_string) # 使用关键字参数 formatted_string_with_keywords = "Name: {n}, Age: {a}".format(n=name, a=age) print(formatted_string_with_keywords) ``` - **f-string(仅限 Python 3.6 及以上版本)** 这是最简洁的方式之一,在性能上也优于其他两种方法。 ```python formatted_fstring = f"Name: {name}, Age: {age}" print(formatted_fstring) ``` #### Java 中的字符串格式化 Java 同样提供了强大的字符串构建工具来完成这一任务: - **利用 `String.format()` 或者 `MessageFormat.format()`** 这两种静态方法允许通过指定模式串以及相应的变量列表创建新的字符串实例。 ```java public class Main { public static void main(String[] args) { String name = "Bob"; int age = 28; // Using String.format() System.out.println(String.format("Name: %s, Age: %d", name, age)); // Or using MessageFormat import java.text.MessageFormat; System.out.println(MessageFormat.format("Name: {0}, Age: {1}", name, Integer.toString(age))); } } ``` 为了保持一致性并减少混淆,当定义自己的类或接口时应遵循既定的方法命名约定;例如,对于能够转换成字符串的对象应该提供名为 `toString` 的无参方法而不是其他的名称。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值