使用StringTokenizer用Asteriks替换3个字母的单词?

时间:2017-04-06 20:10:47

标签: java

想要用" *"替换字符串中的所有3个字母单词,例如,如果有人输入"我忘了问",它会输出" ;我忘了***",这就是我所拥有的,不知道从哪里开始。

public static void main (String[] args)
{
    c = new Console ();


    c.print("Enter a string: ");
    String phrase;
    phrase = c.readLine();

    StringTokenizer phrase = new StringTokenizer (phrase);
    while (phrase.hasMoreTokens ())
    {
        c.print (phrase.nextToken());

    }



} // main method

3 个答案:

答案 0 :(得分:0)

有趣的问题。我使用Java 8解决了你的问题,我刚刚添加了一个简单的测试,证明它有效:

import org.junit.Test;
import static java.util.Arrays.asList;
import static java.util.stream.Collectors.joining;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;

public class SoloTriesToLearn {

    public String wordReplacer(String sentence) {

       return asList(sentence.split(" ")).stream()
               .map(word -> word.length() == 3  ? "***" : word + " ")
               .collect(joining());

    }

    @Test
    public void shouldReplaceWordsWithAsterisk() {
        String result = wordReplacer("I forgot to ask");
        assertThat(result, is("I forgot to ***"));
    }
}

所以基本上我正在做的是首先分割单词,然后我流式传输它们并且我做一个映射来检测长度是否= = 3然后我返回***。在流的末尾,我通过连接将元素收集回单个String。

我希望你发现这段代码很有用,我发现这种操作非常容易使用。

<强>更新 好的,所以如果您的老师不理解Java8,请不要担心使用您想要的Tokenizer的顽皮方式;)

import org.junit.Test;
import java.util.StringTokenizer;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;

public class SoloTriesToLearn {

    public String wordReplacer(String sentence) {

        StringTokenizer st = new StringTokenizer(sentence);
        String acumulator = "";

            while (st.hasMoreElements()) {
                String currentWord = (String) st.nextElement();
                if(currentWord.length() == 3) {
                    acumulator += "***";
                } else {
                    acumulator += currentWord + " ";
                }
            }
        return acumulator;
    }

    @Test
    public void shouldReplaceWordsWithAsterisk() {
        String result = wordReplacer("I forgot to ask");
        assertThat(result, is("I forgot to ***"));
    }
}

答案 1 :(得分:0)

或者只是:

phrase = phrase.replaceAll("\\b[a-zA-Z]{3}\\b", "***");

答案 2 :(得分:-1)

public static void main (String[] args)
{
    Scanner input = new Scanner(System.in);

    System.out.println("Enter a string: ");
    String phrase;
    phrase = input.nextLine();
    ArrayList<String> sentence = new ArrayList<>();

    StringTokenizer tokenizer = new StringTokenizer(phrase);
    while (tokenizer.hasMoreTokens ())
    {
        sentence.add(tokenizer.nextToken());
    }
    for (String word : sentence)
    {
        if (word.length() == 3)
        {
            word = "***";
        }
        System.out.print(word + " ");
    }


} // main method