java:想实现一个长字符串中 整个单词的替换,(某个单词部分符合 则不进行替换)

例如将 test==》text
替换前
"test, and test but not testing.  But yes to test"

替换后:

"text, and text but not testing.  But yes to text"

替换前后 testing 都不发生改变的。

        String ref = "textWord"; // 替换后的值
        String key = "test"; // 要替换的值
        String str = "test, and test but not testing.  But yes to test";
        int kl = key.length();
        List<Integer> list= new ArrayList<>();
        int length = str.length();
        for(int i = 0; i < length; i ++){
            if (i + kl <= length
                    && str.substring(i ,i + kl).equals(key)){
                if (i + kl == length){
                    list.add(i);
                }else if (i == 0){
                    list.add(i);
                }else{
                    String start = str.substring(i + kl, i + kl + 1);
                    String end = str.substring(i + kl, i + kl + 1);
                    if (start.equals(" ") &&  end.equals(" ")
                            ||start.equals(" ") &&  end.equals(",")
                            ||start.equals(" ") &&  end.equals(".")){
                        list.add(i);
                    }
                }
            }
        }

        for(int i = list.size() - 1; i >= 0 ; i --){
            String s = str.substring(0, list.get(i)); // 前
            String e = str.substring(list.get(i) + kl); // 后
            str = s + ref + e;
        }

        System.out.println(str);
        System.out.println(list);

控制台输出

textWord, and textWord but not testing.  But yes to textWord
[0, 10, 44]

用正则表达式去匹配。

\btest\b