Replacing multiple substrings in Java when replacement text overlaps search text

前端 未结 5 737
囚心锁ツ
囚心锁ツ 2021-01-12 20:54

Say you have the following string:

cat dog fish dog fish cat

You want to replace all cats with dogs, all do

5条回答
  •  耶瑟儿~
    2021-01-12 21:30

    I would create a StringBuilder and then parse the text once, one word at a time, transferring over unchanged words or changed words as I go. I wouldn't parse it for each swap as you're suggesting.

    So rather than doing something like:

    // pseudocode
    text is new text swapping cat with dog
    text is new text swapping dog with fish
    text is new text swapping fish with cat
    

    I'd do

    for each word in text
       if word is cat, swap with dog
       if word is dog, swap with fish
       if word is fish, swap with cat
       transfer new word (or unchanged word) into StringBuilder.
    

    I'd probably make a swap(...) method for this and use a HashMap for the swap.

    For example

    import java.util.HashMap;
    import java.util.Map;
    import java.util.Scanner;
    
    public class SwapWords {
       private static Map myMap = new HashMap();
    
       public static void main(String[] args) {
          // this would really be loaded using a file such as a text file or xml
          // or even a database:
          myMap.put("cat", "dog");
          myMap.put("dog", "fish");
          myMap.put("fish", "dog");
    
          String testString = "cat dog fish dog fish cat";
    
          StringBuilder sb = new StringBuilder();
          Scanner testScanner = new Scanner(testString);
          while (testScanner.hasNext()) {
             String text = testScanner.next();
             text = myMap.get(text) == null ? text : myMap.get(text);
             sb.append(text + " ");
          }
    
          System.out.println(sb.toString().trim());
       }
    }
    

提交回复
热议问题