阅读用户的段落并替换java

时间:2017-09-04 15:14:21

标签: java

我们如何使用Java编写程序来读取用户的段落,并将向量中提到的特定单词替换为以下格式,即

例如,单词Happy缩减为H****

任何帮助都会受到影响。

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

class replaceString {

     public static String putStars(String str) {
        char first_char = str.charAt(0);

        String ans = new String();
        ans = String.valueOf(first_char);

        for(int i = 1;i < str.length(); ++i ) {
            ans = ans + "*";
        }
        return ans;
    }

    public static String replaceWords(String str, Vector<String> v1) {
        String[] words = str.split("\\W+"); //split across all types of punctuation

        String ansString = new String();

            for(String to_be_replaced : words) {
                boolean found = false;

                for(String to_replace_with : v1) {

                if(to_be_replaced.equals(to_replace_with)) {
                    //System.out.println("in");
                    ansString = ansString +putStars(to_be_replaced) +  " ";
                    found = true;

                }
            }  
                if(found == false) {
                    ansString = ansString + to_be_replaced + " ";
                }

        }
        return ansString;
    }

        public static String replaceWords1(String str, Vector<String> v1) {

        for(String currStr : v1) {
            str.replace(str, );
        }

        return ansString;
    } 


    public static void main(String args[])throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter the paragraph that you would like to edit ");

        String s = br.readLine();

        // Let us assume some strings in our very own vector

        Vector<String> v1 = new Vector<String>();

        v1.addElement("Hello");
        v1.addElement("Hi");
        v1.addElement("Heya");
        v1.addElement("Howdy");
        v1.addElement("Howu");

        String ans = replaceWords(s, v1);

        System.out.println("Paragraph after replacement becomes\n\n"+ ans);
    }
}

这是我目前的代码,但它不能正常工作

2 个答案:

答案 0 :(得分:2)

尝试使用包含您的地图替换规则的地图:

    String input; //input string
    Map<String,String> mapReplace = new HashMap<String,String>();
    mapReplace.put("Hello","H****");
    Iterator<String> keys = mapReplace.keySet().iterator();
    while(keys.hasNext()){
        String key = keys.next();
        input = input.replace(input, mapReplace.get(key));
    }

答案 1 :(得分:2)

可能还有其他可能性,但这是我基于this answer做的一个例子:

  1. 我们需要所有需要/想要匹配的单词,并将它们存储在一个数组中:

    String [] words = {"appy", "eya", "dy"};
    
  2. (可选)如果您确实需要Vector,我建议改为创建ListArrayList),我们可以这样做:

    List <String> wordsToReplace = Arrays.asList(words);
    

    否则只需在下一步中修改方法即可接收数组......

  3. 我们创建一个函数来接收此List以及我们要检查的短语,并返回包含替换文本的新String

  4. 所以,我们的整个代码最终都是这样的:

    import java.util.Arrays;
    import java.util.List;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    public class WordReplacer {
        public static void main(String[] args) {
            String [] words = {"appy", "eya", "dy"};
    
            List <String> wordsToReplace = Arrays.asList(words);
    
            System.out.println(replaceWords("Happy", wordsToReplace));
            System.out.println(replaceWords("Heya", wordsToReplace));
            System.out.println(replaceWords("Howdy?", wordsToReplace));
            System.out.println(replaceWords("Howdy? My friend lives in Pompeya and every time I see her I say \"Heya\" to her, she is very happy", wordsToReplace));
        }
    
        private static String replaceWords(String word, List <String> wordsToReplace) {
            for (String s : wordsToReplace) {
                Pattern p = Pattern.compile(s, Pattern.CASE_INSENSITIVE); //We create a pattern that matches each word in our list. (1)
                Matcher m = p.matcher(word); //We actually check for each match against our phrase
                StringBuilder sb = new StringBuilder();
                if (m.find()) { //If there was a match, we're going to replace each character for an '*' (2)
                    for (int i = 0; i < s.length(); i++) {
                        sb.append("*");
                    }
                }
    
                word = m.replaceAll(sb.toString()); //We replace each match with '*' (3)
            }
    
            return word; //We return the modified word
        }
    }
    

    我将以更好,更简单的方式解释每条评论(1),(2),(3)的作用:

    • (1)如链接的答案所示,他们使用\b正则表达式命令来匹配整个单词,但在这种情况下,我们使用它来匹配单词的部分,而不是整个单词,所以我们这里不需要它......

    • (2)只有当我们找到匹配项时,我们才会使用StringBuilder字符填充* ...如果我们不这样做,我们会得到:{{对于H*字的情况,1}}而不是H****,这样我们就可以确保为Happy中的每个字获得正确的*数量。

    • (3)我们替换了List*总数的匹配项,以便我们得到正确的输出。

    上述程序产生以下输出:

    StringBuilder