![](/img/trans.png)
[英]How to check if an array containing strings, has certain words in it from another string array
[英]How to add 2 words from an array to a string from another array
我正在为学校编写一个疯狂的 lib 程序。 该程序必须有 30 个句子,每个句子中缺少两个单词。 我计划将句子存储在一个数组中,将用户输入的单词存储在第二个数组中,然后将单词数组中的单词添加到句子数组中的句子中。 当使用 for 循环执行此操作时,它适用于第一句,但在之后的每个句子中都使用相同的单词。
这是我这部分的代码:
String story[] = {"Once upon a time, there was a _ man named _.", "He loved playing _ on _ afternoons."};
String words[] = {"awesome", "James", "checkers", "Sunday"};
for (int i = 0; i < story.length; i++) {
for (int j = 0; j < words.length; j++) {
story[i] = story[i].replaceFirst(placeholder, words[j]); // placeholder is set to '_'
}
System.out.println(story[i]);
}
for (int i = 0; i < story.length; i++) { for (int j = i 2; j < (i 2)+1; j++) { story[i] = story[i].replaceFirst(placeholder,词[j]); // 占位符设置为 '_' } System.out.println(story[i]); }
我想如果你真的想用这种方式解决它,这会起作用
这应该工作
String story[] = {"Once upon a time, there was a _ man named _.", "He loved playing _ on _ afternoons."};
String words[] = {"awesome", "James", "checkers", "Sunday"};
int j=0;
for (int i = 0; i < story.length; i++) {
while(story[i].contains("_")){
story[i] = story[i].replaceFirst("_", words[j++]);
}
System.out.println(story[i]);
}
根据您的情况, words
数组将包含 x2 个元素,而不是story
数组。 我们可以用它来写一个简单的算法:
String story[] = {"Once upon a time, there was a _ man named _.", "He loved playing _ on _ afternoons."};
String words[] = {"awesome", "James", "checkers", "Sunday"};
String placeholder = "_";
for (int i = 0; i < story.length; i++) {
String word1 = words[i * 2];
String word2 = words[i * 2 + 1];
story[i] = story[i]
.replaceFirst(placeholder, word1)
.replaceFirst(placeholder, word2);
System.out.println(story[i]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.