【问题标题】:How to replace a character at random in a string?如何在字符串中随机替换一个字符?
【发布时间】:2017-04-01 11:42:53
【问题描述】:

我已经根据两个给定的值(N,M)打印了一串“+”符号。现在我试图弄清楚如何根据第三个给定值(K)随机替换所述字符串中的字符。字符存储在字符串(l)中。我想我必须使用替换功能,但我不知道如何(因此为什么现在在评论中)。任何帮助表示赞赏。

#include <stdio.h>

unsigned int randaux()
{
  static long seed=1;
  return(((seed = seed * 214013L + 2531011L) >> 16) & 0x7fff);
}

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main() {
    char s[1000];
    int N, M, K, l;

    printf("N: ");
    scanf("%d",&N);
    printf("M: ");
    scanf("%d",&M);
    printf("K: ");
    scanf("%d",&K);
    printf("\n");

    gets(s);

    l=strlen(s);

    /* Mostre um tabuleiro de N linhas e M colunas */

    if(N*M<K){
    printf("Not enough room.");
    }else if(N>40){
    printf("Min size 1, max size 40.");
    }else if(M>40){
    printf("Min size 1, max size 40.");
    }else{      
    for(int i=0; i<N; i++)
    {

    for(int j=0; j<M; j++)
    {
    printf("+", s[j]);
    }   

    printf("\n", s[i]);
    }
    for(int l=0; l<K; l++)
    {
    /*s.replace();*/
    }
}
    return 0;
}

【问题讨论】:

  • 我不明白这个问题。 randaux() 不仅没有被调用,而且如果被调用,它每次都使用相同的种子。
  • 您是否正在尝试“回收”您找到但不是您自己编写的代码?注释掉的s.replace(); 有可能(但不太可能)是 C 代码。
  • @Weather Vane randaux 未被调用,因为我不知道何时调用它。种子目前是静态的,可以用静态结果进行测试。
  • s 是一个字符数组。它没有成员函数,所以s.replace() 在这里无效。
  • 你想用什么替换字符?

标签: c string random replace


【解决方案1】:

您的程序中有太多无法解释的复杂性和未知数,无法提供正确的答案。但这显示了如何用数字随机替换文本字符串的字符。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

int main(void)
{
    char str[] = "----------";
    int len = strlen(str);
    int index;
    int num;

    srand((unsigned)time(NULL));    // randomise once only in the program
    printf("%s\n", str);            // original string

    index = rand() % len;           // get random index to replace, in length range
    num = '0' + rand() % 10;        // get random number, in decimal digit range
    str[index] = num;               // overwrite string character

    printf("%s\n", str);            // altered string
    return 0;
}

计划会议:

----------
-3--------

----------
-----0----

----------
--------6-

可以说使用size_t 类型会更好,但对于示例的有限范围,就足够了。

【讨论】:

    猜你喜欢
    • 2021-06-12
    • 2017-05-20
    • 1970-01-01
    • 1970-01-01
    • 2017-08-06
    • 1970-01-01
    • 2021-07-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多