【问题标题】:Substituting percentage of words at random indexes in String array替换字符串数组中随机索引处的单词百分比
【发布时间】:2015-01-07 21:17:41
【问题描述】:

我有一个类似

的字符串

这是一个非常好的句子

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

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

我怎样才能对总词数(假设 2 个词,共 6 个词)取特定百分比,然后用其他词代替这 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);` 

【问题讨论】:

    标签: android arrays string random words


    【解决方案1】:

    首先,计算你要替换多少个单词:

    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,2是6个单词的33.33%。

    【讨论】:

    • 如果我想要前两个和后两个常量索引,我会这样做..int index = random.nextInt((maxIndex-2)-2);
    • 我想在 totalWordsCount 上设置边界。例如,如果 totalWordsCount 是 14 ,我想要从 2 到 12 的随机数。
    • 对于 14 个单词,如果随机数介于 2 和 12 之间,则 int index = 2 + random.nextInt(11);然后制定出与变量一起使用的公式。注意:记住,如果你有 14 个单词,你想要的最大索引是 13,而不是 14。
    猜你喜欢
    • 2017-03-24
    • 1970-01-01
    • 2021-05-29
    • 2012-05-29
    • 2017-11-03
    • 1970-01-01
    • 1970-01-01
    • 2017-05-20
    • 2019-04-24
    相关资源
    最近更新 更多