如果您检查是否包含新单词并且分隔符是 \n 那么您将需要正则表达式。仅依靠 contains 不会添加现有单词的子序列的单词。
public class AddWords {
public String addWord(final String newWord, final String allWords) {
String result = allWords;
Pattern p = Pattern.compile(".*\n" + newWord + "\n.*");
Matcher m = p.matcher(allWords);
if (!m.find()) {
StringBuffer buf = new StringBuffer();
buf.append(allWords);
buf.append(newWord);
buf.append("\n");
result = buf.toString();
}
return result;
}
}
为了更好地理解此事,我为该场景添加了一个单元测试:
public class AddWordsTest {
@Test
public void addExistingWord() {
String allWords = "\nfoo\nbar\n";
String notNewWord = "foo";
AddWords aw = new AddWords();
String newAllWords = aw.addWord(notNewWord, allWords);
Assert.assertEquals(allWords, newAllWords);
}
@Test
//This would fail if you rely on contains!!!
public void addNewWord() {
String allWords = "\nfoobar\nbar\n";
String newWord = "foo";
AddWords aw = new AddWords();
String newAllWords = aw.addWord(newWord, allWords);
String expectedAllWords = "\nfoobar\nbar\nfoo\n";
Assert.assertEquals(expectedAllWords, newAllWords);
}
}