有趣的问题。我解决了使用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,这里就不担心使用标记生成你想要的调皮方式;
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 ***"));
}
}
检查单词的'.length()',如果是3打印'***'else print word? – Pshemo
'String phrase = c.readLine()。replaceAll(“\\ D {3}”,“***”);' –
我会把那行放在c.print? – SoloTriesToLearn