zoukankan      html  css  js  c++  java
  • 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;
        }

    以上代码可实现一次高亮,余下的问题就在于如何多次改变字符串的长度后能定位到需要更改的字符串(即多次高亮),打个卡先,有空再弄

  • 相关阅读:
    默哀STAND SILENTLY!
    用虚拟机优化Windows(update:2008.4.24)
    UE的心情指数?
    God of War III 的发售日期?
    2009/8/15应该是一个愉快的夜晚.为林肯公园中国10月演唱会做好准备
    北京2008奥运会完美谢幕!
    《The Pursuit of Happyness / 当幸福来敲门》(2006)
    2007林肯公园上海演唱会观后感(实况像片/MP3) update:2008.1.31
    2008早上好
    Active Object C++智能指针实现
  • 原文地址:https://www.cnblogs.com/yuan-zhou/p/12010918.html
Copyright © 2011-2022 走看看