Java 如何每次用数组中的随机元素替换字符串变量中的多个单词?

Java 如何每次用数组中的随机元素替换字符串变量中的多个单词?,java,arrays,string,loops,arraylist,Java,Arrays,String,Loops,Arraylist,我有一个字符串变量,每次出现另一个%时,我想用数组中的不同元素替换占位符(%)。如何创建一个循环,在字符串变量的每个占位符(%)中随机插入不同的单词。记住,理想的解决方案是使用循环 //This is the code I have so far ArrayList<String> wordsList = ... String sentence = "A % is a series of related sentences developing a central %,

我有一个字符串变量,每次出现另一个%时,我想用数组中的不同元素替换占位符(%)。如何创建一个循环,在字符串变量的每个占位符(%)中随机插入不同的单词。记住,理想的解决方案是使用循环

//This is the code I have so far

ArrayList<String> wordsList = ...

String sentence = "A % is a series of related sentences developing a central %, called the %. Try to think about paragraphs in terms of thematic unity: a paragraph is a % or a group of % that supports one central, unified idea";

Random rand = new Random();

libStory = sentence.replace("%", wordsList.get(rand.nextInt(wordsList.size())));

    System.out.println(sentence);
但是使用replace函数,我得到

String句子=“A(RANDOMWORD1)是一系列相关的句子,它们形成了一个中心(RANDOMWORD1),称为(RANDOMWORD1)。试着从主题统一的角度来思考段落:一个段落是一个(RANDOMWORD1)或一组(RANDOMWORD1),支持一个中心统一的想法”


我尝试使用的循环是

while((line = wordReader1.readLine()) != null){
  randIndex = rand.nextInt(wordsList.size());

  sentence = sentence.replace("%",wordsList.get(randIndex));

  }
我还有这个

for (int i = 0; i < sentence.length(); i++) {
   randIndex = rand.nextInt(wordsList.size());

   sentence = sentence.replace("%",wordsList.get(randIndex));
for(int i=0;i<句子长度();i++){
randIndex=rand.nextInt(wordsList.size());
句子=句子.replace(“%”,wordsList.get(randIndex));

}

假设一个元素可以被多次选择(但无论选择与否仍然是随机的):


但是这段代码从字符串的开头开始搜索每个“%”。也就是说,如果您愿意,可以对其进行优化。

类字符串中的
replace
方法将所有出现的char/CharSequence替换为替换char/CharSequence。 您需要的是
replaceFirst
方法,并用于逐个替换%char/字符串。可能与
indexOf
方法结合使用,以检查字符串中是否仍存在%。

//您的arraylist

ArrayList<String> wordsList = ...;
//你的判决

sentence = "A % is a series of related sentences developing a central %, called the %. Try to think about paragraphs in terms of thematic unity: a paragraph is a % or a group of % that supports one central, unified idea";
//使用占位符将其拆分(%)

//开始循环和插入

sentence = "";
count = 0;
for(String i : s){
   if(count >= wordsList.size()){
      count = 0;
      Collections.shuffle(wordsList);
   }
   sentence = sentence + i + wordsList[count];
   count = count + 1;

print(sentence);
//即使“%”在字符串的开头、结尾或中间,它也可以正常工作。

replace(target,replacement)
就像
replaceAll(target,replacement)
替换与
目标匹配的所有部分一样

这两种方法之间唯一的区别是
replaceAll
支持正则表达式语法,而
replace
则逐字处理文本

如果希望能够为可以使用的每个匹配动态指定替换。此方法不包括
函数
决定每个匹配项的替换

在你的情况下,它可能看起来像

//Random rand        = ...; 
//List<String> words = ...;

match -> words.get(rand.nextInt(words.size()))
//       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-- part responsible for picking random 
//                                               word from `List<String> words`.

显然,在Java中有很多方法可以实现这一点,但一个简单的方法是使用
String.indexOf
的变体,它允许您从给定位置进行搜索。通过使用先前识别的位置作为起点,您可以识别
%
的每个匹配项,并将其替换为随机选择的单词

List<String> wordsList = Arrays.asList("WORD1", "WORD2", "WORD3", "WORD4", "WORD5");

String sentence = "A % is a series of related sentences developing a central %, called the %. Try to think about paragraphs in terms of thematic unity: a paragraph is a % or a group of % that supports one central, unified idea";

Random rand = new Random();

StringBuilder b = new StringBuilder();
for(int idx=0;;)
{
    int nidx = sentence.indexOf("%", idx);      
    if(nidx < 0) 
    {
        b.append(sentence.substring(idx));
        break;
    }
    b.append(sentence.substring(idx, nidx));
    b.append(wordsList.get(rand.nextInt(wordsList.size())));
    idx = nidx+1;
}

System.out.println(b.toString());

你已经知道你需要一个循环,但是我在你的尝试中没有看到一个循环。为什么?问题是什么?我尝试使用循环,但循环使用相同的随机数组元素用相同的单词替换所有占位符。发布生成“不正确”解决方案的代码后,我的问题在于循环(我没有在这里包括它b/c它没有用,也不能正常工作)@谢谢你,但是当我试图运行代码时,我得到了一个错误-语句[index]。错误为“需要数组,但找到字符串”。这是否意味着,我应该将字符串中的每个单词转换为数组元素@如果
单词
可以在正则表达式替换中使用一些特殊字符(这里是
$
\
),则应该在
Matcher.quoteReplacement
中包装替换,如
match->Matcher.quoteReplacement(words.get(rand.nextInt(words.size()))
for(i在s中)可以在java中使用吗,或者是javascript@MALNEEDIVAMSIOh抱歉,我提到了python的“for”循环。我现在为Java更新了它
 s = sentence.split('%');
sentence = "";
count = 0;
for(String i : s){
   if(count >= wordsList.size()){
      count = 0;
      Collections.shuffle(wordsList);
   }
   sentence = sentence + i + wordsList[count];
   count = count + 1;

print(sentence);
//Random rand        = ...; 
//List<String> words = ...;

match -> words.get(rand.nextInt(words.size()))
//       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-- part responsible for picking random 
//                                               word from `List<String> words`.
class Demo {

    static String replaceRandomly(String toReplace, String text, List<String> words){
        Random rand = new Random();
        return Pattern.compile(toReplace, Pattern.LITERAL)
                      .matcher(text)
                      .replaceAll(match -> words.get(rand.nextInt(words.size())));

    }

    public static void main(String[] args){
        List<String> wordsList = List.of("WORD1","WORD2","WORD3");
        String sentence = "A % is a series of related sentences developing a central %, " +
                "called the %. Try to think about paragraphs in terms of thematic " +
                "unity: a paragraph is a % or a group of % that supports one central, " +
                "unified idea";

        System.out.println(replaceRandomly("%", sentence, wordsList));
    }

}
A WORD1 is a series of related sentences developing a central WORD1, called the WORD3. Try to think about paragraphs in terms of thematic unity: a paragraph is a WORD3 or a group of WORD2 that supports one central, unified idea
List<String> wordsList = Arrays.asList("WORD1", "WORD2", "WORD3", "WORD4", "WORD5");

String sentence = "A % is a series of related sentences developing a central %, called the %. Try to think about paragraphs in terms of thematic unity: a paragraph is a % or a group of % that supports one central, unified idea";

Random rand = new Random();

StringBuilder b = new StringBuilder();
for(int idx=0;;)
{
    int nidx = sentence.indexOf("%", idx);      
    if(nidx < 0) 
    {
        b.append(sentence.substring(idx));
        break;
    }
    b.append(sentence.substring(idx, nidx));
    b.append(wordsList.get(rand.nextInt(wordsList.size())));
    idx = nidx+1;
}

System.out.println(b.toString());
A WORD4 is a series of related sentences developing a central WORD3, called the WORD2. Try to think about paragraphs in terms of thematic unity: a paragraph is a WORD2 or a group of WORD5 that supports one central, unified idea