java查找字符中的某个内容并替换

// 查找某内容存在次数

public static int searchEleNum(String str,String targetEle) {
        if( str.indexOf(targetEle) == -1 ) {
            return 0;
        }else {
            return 1 + searchEleNum( str.substring( str.indexOf( targetEle ) + 1 ),targetEle);
        }
    }
    
    // 替换全部
    public static String replaceAll(String parent,String targetEle,String replaceEle ) {
        if( parent.indexOf(targetEle) == -1 ) {
            return parent;
        }else {
            int beginIndex = parent.indexOf(targetEle);
            int endIndex = beginIndex + targetEle.length();
            return parent.substring(0,beginIndex) + replaceEle + replaceAll(parent.substring(endIndex), targetEle, replaceEle);
        }
        
    }

 

int num = xxx.searchEleNum(content,"{{name}}"); //查找存在次数

xxx.replaceAll(content,"{{name}}",name);  //替换

 

posted @ 2020-04-24 10:29  ToDarcy  阅读(4944)  评论(0编辑  收藏  举报