Java實現文本中的關鍵字高亮,匹配所有長度


這個方法還不完整,后面想起來再看,直接放代碼

    public static String getHeightlightWord(String textWord, String key){
        StringBuffer sb = new StringBuffer("");
        String tempWord = textWord == null? "" : textWord.trim();
        String tempKey = key == null? "" : key.trim();
        if("".equals(tempWord) || "".equals(tempKey)){
            return tempWord;
        }else {
            sb.append(tempWord);
        }
        String upperWord = tempWord.toUpperCase();
        String upperKey = tempKey.toUpperCase();
        if(!upperWord.contains(upperKey)){
            return tempWord;
        }else {
            int keyLen = upperKey.length();
            int thisMathIndex = 0;
            List<Map<Integer, String>> matchList = new ArrayList<Map<Integer, String>>();
            while((thisMathIndex = upperWord.indexOf(upperKey, thisMathIndex)) != -1){
                Map<Integer, String> map = new HashMap<Integer, String>();
                map.put(thisMathIndex, tempWord.substring(thisMathIndex, thisMathIndex + keyLen));
                matchList.add(map);
                thisMathIndex += keyLen;
            }
            int thisKey = 0;
            int keys = 0;
            for(Map<Integer, String> map : matchList){
                thisKey = getKey(map);
                keys += thisKey;
                sb.replace(thisKey, thisKey + keyLen, "<span style='background-color: yellow;'>"+map.get(thisKey)+"</span>");
                keys += "<span style='background-color: yellow;'></span>".length();
            }
        }
            return sb.toString();
        }
    private static int getKey(Map<Integer, String> obj){
        Set<Integer> keySet = obj.keySet();
        int firstKey = -1;
        for(int key : keySet){
            firstKey = key;
            if(firstKey != -1){
                break;
            }
        }
        return firstKey;
    }

以上代碼可實現一次高亮,余下的問題就在於如何多次改變字符串的長度后能定位到需要更改的字符串(即多次高亮),打個卡先,有空再弄


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM