繁体   English   中英

如何随机替换字符串中的字符?

[英]How to replace a character at random in a string?

我已经基于两个给定的值(N,M)打印出一串“ +”符号。 现在,我试图找出如何根据第三个给定值(K)随机替换所说字符串中的字符。 字符存储在字符串(l)中。 我想我必须使用replace函数,但是我不知道如何(因此为什么现在在注释中)。 任何帮助表示赞赏。

#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;
}

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

#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类型会更好,但是对于示例的有限范围,就足够了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM