簡體   English   中英

遍歷字符串中的字符

[英]Loop through characters in a string

我將如何遍歷字符串中的每個字符,然后將該字符設置為其他字符呢? 當然,除非有更好的方法來做我想做的事。 我正在創建一個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
}

如果有人可以幫助我,將不勝感激。

您可以使用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消息

關於*******的***條消息

更新-示例代碼以星號替換被禁止的單詞

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.

首先,您不能直接在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);
        }
    }

該代碼使您可以將*的每個字符都打印為*,直到沒有空格為止,因此,如果您的單詞是香蕉,他將打印********

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);

答案: ********

希望我能解決您的問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM