英文:
How to write a method that returns strings that contain every object from an array
问题
我想编写一个方法,该方法以数组(而非ArrayList)作为参数。该方法应检查多个字符串是否包含数组中指定的所有单词,然后返回包含这些单词的字符串。是否可以只使用for循环和字符串方法来实现这个目标?
我尝试过类似以下的方式:
public String text(String[] words) {
String concatedStrings = "";
for (int i = 0; i < numStrings.length; i++) {
if (numStrings[i] != null) {
for (int j = 0; j < words.length; j++) {
if (numStrings[i].contains(words[j])) {
concatedStrings += numStrings[i];
}
}
}
}
return concatedStrings;
}
英文:
I want to write a method that has an array (not arrayList) as a parameter. That method should check if multiple strings contain all the words stated in the array, and therefore returns strings that do. Is there a way of doing it just by using for loops and string methods?
I tried to do something like this:
public String text (String[] words) {
String concatedStrings = "";
for(int i = 0; i < numStrings.length; i++) {
if(numStrings[i] != null) {
for(int j = 0; j < words.length; j++) {
if(numStrings[i].contains(words[j])) {
concatedStrings += numStrings[i];
}
}
}
}
return concatedStrings;
}
答案1
得分: 0
你的代码是正确的,但需要对它进行一些修改。
public String text(String[] words, String[] strings) {
String concatedStrings = "";
for (String s : strings) { // 遍历所有字符串
boolean containsAllWords = true;
for (String word : words) { // 检查当前字符串是否包含所有单词
if (!s.contains(word)) {
containsAllWords = false;
break;
}
}
if (containsAllWords) {
concatedStrings += s;
}
}
return concatedStrings;
}
在主方法中:
String[] words = {"hello", "world"};
String[] strings= {"hello world", "world hello", "hello there"};
英文:
Your code is correct but needs some modification on your code.
public String text(String[] words, String[] strings) {
String concatedStrings = "";
for (String s : strings) { // loop through all the strings
boolean containsAllWords = true;
for (String word : words) { // check if the current string contains all the words
if (!s.contains(word)) {
containsAllWords = false;
break;
}
}
if (containsAllWords) {
concatedStrings += s;
}
}
return concatedStrings;
}
in main method:
String[] words = {"hello", "world"};
String[] strings= {"hello world", "world hello", "hello there"};
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论