循环遍历字符串中的字符

时间:2015-10-24 20:21:07

标签: java string for-loop replace char

如何循环字符串中的每个字符,然后将该字符设置为其他字符?除非当然有更好的方法来做我想做的事情。我正在创建一个Bukkit插件,它将根据它包含的内容更改聊天消息中的单词。以下是我到目前为止的情况:

for (String word : e.getMessage().split(" ") {
    if (wordList.contains(word)) {
        e.setMessage(e.getMessage.replaceAll(word, "*");
    }
}

但是,我希望能够设置单词中的每个字符,而不是设置整个单词。我试过这样的东西,但我的IDE并不喜欢它。请注意,这是基于上面的代码,并且如果wordList包含单词,则在检查范围内。

for (char c : word.toCharArray()) {
    // there are no available methods for editing the char c
}

如果有人可以帮我解决这个问题,我们将不胜感激。

3 个答案:

答案 0 :(得分:0)

您可以使用java.util.regex.Pattern类和匹配每个字符的正则表达式来替换每个字符。

ArrayList<String> wordList = new ArrayList<String>();
wordList.add("foo");
wordList.add("carrots");

String message = "The foo bar message about carrots";

// use this class to match each character with the regex dot
Pattern p = Pattern.compile(".", Pattern.DOTALL);
// use to create the new message from the words (some replaced with asterisk)
StringBuffer newMessage = new StringBuffer();
// loop through each word
for (String word : message.split(" ") ){
    // if it is in your list....
    if (wordList.contains(word)) {
        // add it to newMessage, but replaced by asterisk.
        newMessage.append(p.matcher(word).replaceAll("*"));
    } else {
        // add the unmodified word
        newMessage.append(word);
    }
    // add a space before we loop to the next word
    newMessage.append(" ");
}
// set the new message string with some words replaced
message = newMessage.toString().trim();
System.out.println(message);

运行时会输出以下文字:

  

关于胡萝卜的foo bar消息

     

关于*******的***栏消息

UPDATE - 用星号替换被禁词的示例代码

public static void main(String[] args) {
    // Your input string
    String message = "The foo bar message about carrots. Carrots suck so do parrots. Parrotsucker is partially masked. Carrots was already replaced.";
    System.out.println(message);

    // An array of words you want to mask
    ArrayList<String> wordList = new ArrayList<String>();
    wordList.add("foo");
    wordList.add("carrots");
    wordList.add("parrots");

    // Create a regex to match the banned words.... in this case it will be "foo|carrots|parrots", case insensitive
    String regex = Arrays.toString(wordList.toArray());
    regex = regex.substring(1, regex.length()-1).replaceAll(", ", "|");
    Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
    System.out.println("Regex: " + p);

    // Keep track of the asterisks strings by length so we don't generate more than once
    Map<Integer, String> maskMap = new HashMap<Integer, String>();
    // Since we use replaceAll we might get a match more than once, so we can track and skip once that have already been handled
    Vector<String> replaced = new Vector<String>();
    // Find a list of banned words in the input message
    Matcher m = p.matcher(message);
    // Loop over each of the matches
    while (m.find()){
        // Get the text of each match
        String match = m.group();
        // Have we already replaced it in the message?
        if ( !replaced.contains(match) ){
            // This is what we will replace it with
            String mask = null;
            // See if we have a string the same length as the current match
            if ( maskMap.containsKey(match.length())) {
                // If so, get it out of the map.
                mask = maskMap.get(match.length());
                System.out.println("Got mask from maskMap: " + mask);
            } else {
                // No mask, so generate one and save it in the Map
                StringBuffer maskBuffer = new StringBuffer("*");
                while ( maskBuffer.length() < match.length() ){
                    maskBuffer.append("*");
                }
                mask = maskBuffer.toString();
                maskMap.put(mask.length(), mask);
                System.out.println("Generated new entry for maskMap: " + mask);
            }
            // Replace the matched banned word with the correct mask
            message = message.replaceAll(match, mask);
            // Track that we already replaced this word
            replaced.add(match);
            System.out.println((new StringBuffer("   Replaced '").append(match).append("' with '").append(mask).append("'")).toString());
        } else {
            System.out.println("Aready replaced: " + match);
        }
    }

    // The message with banned words masked.
    System.out.println(message);

    System.exit(0);

}

产生以下输出:

The foo bar message about carrots. Carrots suck so do parrots. Parrotsucker is partially masked. Carrots was already replaced.
Regex: foo|carrots|parrots
Generated new entry for maskMap: ***
   Replaced 'foo' with '***'
Generated new entry for maskMap: *******
   Replaced 'carrots' with '*******'
Got mask from maskMap: *******
   Replaced 'Carrots' with '*******'
Got mask from maskMap: *******
   Replaced 'parrots' with '*******'
Got mask from maskMap: *******
   Replaced 'Parrots' with '*******'
Aready replaced: Carrots
The *** bar message about *******. ******* suck so do *******. *******ucker is partially masked. ******* was already replaced.

答案 1 :(得分:0)

首先,你不能直接在String中修改任何字符,因为String是不可变的。

或者,您可以在合并所需字符后创建新字符串。

看看这段代码:

        String word = "Look";
        String modifiedWord = word.substring(0,1) + "***" + word.substring(word.length()-1);
        System.out.println(modifiedWord);

如果您只需要在匹配的字符串体内设置符号,而不是在字符串的开头和结尾处设置符号,则可以尝试此操作。

Output: L***k

您的代码可以修改如下:

   String modifiedWord = null;
    for (String word : e.getMessage().split(" ") {
        if (wordList.contains(word)) {
            modifiedWord = word.substring(0,1) + "***" + word.substring(word.length()-1);
            e.setMessage(e.getMessage.replaceAll(word, modifiedWord);
        }
    }

答案 2 :(得分:-1)

该代码会让你打印更改每个角色的*,直到没有空格,所以如果你的单词是 banana ,他将打印********

char[] c= word.toCharArray();

    String newString ="";
    for (int i = 0; i < c.length; i++) {
            if(c[i] != ' ' ) newString += "*";
    }
    System.out.println(newString);

修改

如果您还想更改一个句子,请更改为

String word = "foo  woord";
    char[] c= word.toCharArray();

    String newString ="";
    for (int i = 0; i < c.length; i++) {
            if(c[i] != ' ' ) newString += "*";
            else newString += " ";
    }
    System.out.println(newString);

答案: **** ******

希望我能解决你的问题