替换字符串数组中随机索引处的单词百分比
Substituting percentage of words at random indexes in String array
我有一个像
这样的字符串
This is a very nice sentence
我把它分解成单独的词并存储在 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);`
首先,计算一下你要替换多少个字:
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
}
注意:请记住,字数越少,您的百分比与要替换的实际字数之间的差异就越大,例如。 20% from 6 words 是1.2 word,经过Math.ceil()后变成2,而2 is 33.33% from 6.
我有一个像
这样的字符串This is a very nice sentence
我把它分解成单独的词并存储在 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);`
首先,计算一下你要替换多少个字:
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
}
注意:请记住,字数越少,您的百分比与要替换的实际字数之间的差异就越大,例如。 20% from 6 words 是1.2 word,经过Math.ceil()后变成2,而2 is 33.33% from 6.