簡體   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