【问题标题】:How to add a common string in every randomly generated string Javascript如何在每个随机生成的字符串 Javascript 中添加一个公共字符串
【发布时间】:2016-05-28 21:49:20
【问题描述】:

我正在使用 node.js 中的以下函数生成随机字符串。我想知道是否有任何方法可以在每个随机生成的字符串中使用 common string 适当地创建文本字符串。

编辑:通用字符串可以在生成字符串的任何位置

例如:

随机生成的字符串 - Cxqtooxyy4

我可以像这样在该字符串中添加 'abc''ABC' - Cxqtoabcoxyy4CxqtoABCoxyy4

我的代码 -

var randomTextArrayGeneration = function(size)
{
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    for(var i=0;i<size;i++)
        text += possible.charAt(Math.floor(Math.random() * possible.length));
    return text;
}

谁能告诉我该怎么做?任何帮助都非常有帮助。

【问题讨论】:

  • 公共字符串是否应该总是在随机字符串中的相同位置?如果指定的size 比普通字符串短怎么办?
  • 有点不清楚您的要求。嵌入的字符串是否每次都需要位于相同的位置?每次都需要在随机位置吗?它在哪里不重要吗?
  • 抱歉没有正确解释。嵌入的字符串可以在任何位置。
  • 你能...是的,当然。通过查看网络上许多地方记录的各种子字符串/操作方法并至少尝试一下,应该不难了解如何进行
  • 任何位置?那么为什么不在生成长度大小为-3的随机字符串(假设固定字符串的长度为3)之后将其放在末尾。

标签: javascript node.js string random


【解决方案1】:
var n = text.length; //The size of your random string
var randomPosition = Math.floor((Math.random() * n) + 1); //Generate a  random number between 1 and the size of your string

//Separate your string in 2 strings
var text1 = text.substring(1, randomPosition); 
var text2 = text.substring(randomPosition, n); 

//Create your final string by adding the common string between your two halves
var textFinal = text1 + commonString + text2;

return textFinal;

我不记得具体是如何工作的 .substring(),您可能想在某些地方将 1 更改为 0。

【讨论】:

    【解决方案2】:

    算法的粗略草图是这样的:

    1. 创建长度为size - &lt;FIXED_STRING&gt;.length的随机字符串
    2. &lt;FIXED_STRING&gt;附加到生成字符串的末尾

    完成。

    一个极端情况是size &lt; &lt;FIXED_STRING&gt;.length,在这里你需要提供更多关于应该发生什么的讨论。

    【讨论】:

    • 感谢您的回答 :) 它给了我一个想法,我也可以自己尝试一下 :)
    【解决方案3】:

    您可以使用String.prototype.slice()possible 中选择0-n 个字符,以插入从randomTextArrayGeneration 返回的字符串中的随机索引。如果将0 传递给randomTextArrayGeneration,则来自possible 的选定字符串将被设置为结果

    var randomTextArrayGeneration = function(size, from, to) {
          var text = "";
          var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
          for (var i = 0; i < size; i++) {
            text += possible.charAt(Math.floor(Math.random() * possible.length))
          };
          var len = Math.floor(Math.random() * text.length - 3);
          var res = text.slice(0, len) + possible.slice(from, to).toLowerCase() + text.slice(len);
          return res
    }
    

    【讨论】:

    • 谢谢你的回答:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-23
    • 2011-07-23
    • 2022-11-12
    • 1970-01-01
    • 1970-01-01
    • 2018-06-04
    相关资源
    最近更新 更多