有趣的問題。我解決了使用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