我正在尝试编写一个方法findChar()。此方法将字符和字符串数组作为参数,并打印数组中包含指定参数字符的所有单词。 例如
Test Result
String[] words = {"caravan", "car", "van", "bike", "scooter", "vehicle", "bicycle"};
findChar('v', words); Words containing the letter v : caravan van vehicle
findChar('i', words); Words containing the letter i : bike vehicle bicycle
我现在得到类似的东西这是一个粗略的想法,但不是100%肯定,因为我还有一周学习java所以请放轻松。
public static void findChar(Char character, String word) {
for(String word:words) {
// Check if it contains the character
if (word.contains(Character.toString(character))) {
wordsContainingCharacter.add(word);
}
if(.....size() > 0) {
System.out.println("Words containing the letter " + character + " : " + ....);
} else {
System.out.println("Character is not in any word");
}
}
}
答案 0 :(得分:3)
这应该有效
public static void findChar(char character, String words[]) {
//ArrayList for putting the matched words
ArrayList<String> wordsContainingCharacter = new ArrayList<String>();
for (String word : words) {
// Check if it contains the character
if (word.contains(Character.toString(character))) {
wordsContainingCharacter.add(word);
}
}
//2.check is to be put after the loop
if (wordsContainingCharacter.size() > 0) {
System.out.println("Words containing the letter " + character
+ " : " + wordsContainingCharacter);
} else {
System.out.println("Character is not in any word");
}
}
不使用ArrayList的逻辑
StringBuilder stringOfWords=new StringBuilder();
for (String word : words) {
// Check if it contains the character
if (word.contains(Character.toString(character))) {
stringOfWords.append(word+" ");
}
}
//2.check is to be put after the loop
if (stringOfWords.length() > 0) {
System.out.println("Words containing the letter " + character
+ " : " + stringOfWords);
} else {
System.out.println("Character is not in any word");
}