天天看點

String 字元串截取,獲得指定字元數量,截取String兩個内容之前内容并去重

String 字元串截取,獲得指定字元數量,截取String兩個内容之前内容并去重

将内容替換為指定内容

我的需替換字元是以“?“包裹 例:”?username?“ 替換為 ”張三“

擁有多個”?xxx?“要替換

public String smsSplicing(String content, Map<String,String> map,String replace){
        int n = 0;			//記錄 ?數量
        String content1 = content;		//定義變量接收内容
        HashSet list = new HashSet();	//使用hashSet去重
        while(content1.indexOf(replace)!=-1) {
            int i = content1.indexOf('?');	//擷取第一個?下标
            n++;
            content1 = content1.substring(i+1);   //擷取第一個?往後的是以字元串
            if(n%2!=0) {
                list.add(content1.substring(0, content1.indexOf("?"))); //擷取下一個?下标進行截取獲得?包裹字元
            }
        }
        if(map.size()!=list.size()){  //判斷傳入參數是否與内容需替換參數相等
            return "xx";
        }
        Set<Map.Entry<String, String>> entry =  map.entrySet(); 
        for (Map.Entry<String, String> m : entry) {
            if (m.getValue()==""||m.getValue().isEmpty()){
                return "5";
            }
            String key = m.getKey();
            String value = m.getValue();
            log.info(key+"---"+value);
            String replaces = replace+key+replace;
            if (content.contains(replaces)==true){
                content = content.replace(replaces,value);
                log.info(content);
            }else {
                return "4";
            }
        }
        log.info("拼接後的内容:"+content);
        return content;
    }