我有这个字符串:

String line = "Hello John; , my name is also John.";


和这个字符串:

String word = "John";
char c = "-";


并希望此输出:

"Hello -John-; , my name is also -John-."


到目前为止,这是我设法做到的:

public String changeString(String line, String word, char c){

String result = null;

    if(line.toLowerCase().contains(word.toLowerCase())){

        result = line.replaceAll(word, c + word + c);

    }

return result;
}


但是,使用此功能,我得到以下输出:

 String result = "Hello -John;- , my name is also -John.-";


我该如何解决?

更新:

如果我只有一个单词而不是一个数组,我该如何工作?

import java.util.*;
import java.lang.*;
import java.io.*;


class Text
{
    public static void main(String[] args) throws Exception {
        String line = "Hello John; , my name: is also John.";
        String[] words = {"John","name"};
        char c = '-';
        changeString(line, words, c);



 }

 public static void changeString(String line, String[] words, char c) {
    String result = null;

    for(int i = 0; i < words.length; i++){
        if (line.toLowerCase().contains(words[i].toLowerCase())) {
            result = line.replaceAll(words[i], c + words[i] + c);
        }
        else
            result = line;
    }
    System.out.println(result);
    }
}


由于不需要输出:

"Hello John; , my -name-: is also John."

最佳答案

代替 :

result = line.replaceAll(word, c + word + c);


采用:

result = line.replace(word, c + word + c);


撇开笔记:

您可能正在使用约翰。而不是john和replaceAll api使用正则表达式作为参数。字符也用单引号而不是像char c = '-';这样的双引号定义

07-26 09:38
查看更多