替换String数组中随机索引的单词百分比(Substituting percentage of words at random indexes in String array)

系统教程 行业动态 更新时间:2024-06-14 17:01:34
替换String数组中随机索引的单词百分比(Substituting percentage of words at random indexes in String array)

我有一个字符串

这是一个非常好的句子

我把它分成单独的单词并存储在String[]中:

String[] words = s.split(" ");

如何对单词总数采取特定的百分比(比如说6个单词中的2个),并用其他内容替换这2个单词。 我的代码到目前为止:

//Indexes in total int maxIndex = words.length; //Percentage of total indexes double percentageOfIndexes = 0.20; //Round the number of indexes int NumOfIndexes = (int) Math.ceil( maxIndex * (percentageOfIndexes / 100.0)); //Get a random number from rounded indexes int generatedIndex = random.nextInt(NumOfIndexes);`

I have a string like

This is a very nice sentence

I break it into separate words and store in String[] with:

String[] words = s.split(" ");

How can I take a specific percentage on the total number of words (lets say 2 of 6 words) and substitute these 2 words with something else. My code so far:

//Indexes in total int maxIndex = words.length; //Percentage of total indexes double percentageOfIndexes = 0.20; //Round the number of indexes int NumOfIndexes = (int) Math.ceil( maxIndex * (percentageOfIndexes / 100.0)); //Get a random number from rounded indexes int generatedIndex = random.nextInt(NumOfIndexes);`

最满意答案

首先,计算要替换的单词数:

int totalWordsCount = words.length; double percentageOfWords = 0.20; int wordsToReplaceCount = (int) Math.ceil( totalWordsCount * percentageOfWords );

然后,知道要替换多少个单词,获取那么多随机索引,然后在这些索引处交换单词:

for (int i=0; i<wordsToReplaceCount; i++) { int index = random.nextInt(totalWordsCount); //and replace words[index] = "Other"; // <--- insert new words }

注意:请记住,单词数量越少,您的百分比与要替换的实际单词数之间的差异就越大,例如。 6个单词中的20%是1.2个单词,在Math.ceil()之后变为2,并且从6开始变为2的33.33%。

First, calculate how many words you want to replace:

int totalWordsCount = words.length; double percentageOfWords = 0.20; int wordsToReplaceCount = (int) Math.ceil( totalWordsCount * percentageOfWords );

Then, knowing how many words you want to replace, get that many random indexes, and just swap words at those indexes:

for (int i=0; i<wordsToReplaceCount; i++) { int index = random.nextInt(totalWordsCount); //and replace words[index] = "Other"; // <--- insert new words }

NOTE: Just remember that the smaller the number of words, the bigger discrepancy between your percentage, and actual number of words to replace, eg. 20% from 6 words is 1.2 word, which becomes 2 after Math.ceil(), and 2 is 33.33% from 6.

更多推荐

本文发布于:2023-04-20 18:55:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/46ed3336861828798ea302fa6b52a76c.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:百分比   单词   组中   索引   String

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!