希望用“*”替换字符串中的所有 3 个字母单词,例如,如果有人输入“I forgot to ask”,它会输出“I forgot to ***”,这就是我所拥有的,不知道从这里去哪里。
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
最佳答案
有趣的问题。我使用 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,然后返回 ***。在流的末尾,我通过加入将元素收集回单个字符串。
我希望你觉得这段代码有用,我发现函数式方法对于这种操作来说非常简单。
更新 好的,所以如果你的老师不了解 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 ***"));
}
}
关于java - 使用 StringTokenizer 将 3 个字母的单词替换为星号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43264901/