samedi 26 mars 2016

C Program To Generated Random Uppercase String and Replace Values

First C programming class and beginning to learn programming. We are currently learning arrays in C and this is a learning task to help understand arrays and get a program that will create a random string of capital letters, then ask for user input of up to 20 uppercase letters, and then replace those letters within the previously random string generated with a *. I can get the random string to generate, however, I am having issues understanding what is the best way to pass that string to the second function to replace the selected values.

Brief Example:

Random string: AOIHGGDGIYGDYFDYIGDGPIGD

Enter letters to replace (up to 20 letters): GD

New string: AOIH****IYYF*YI***PI

Below is the code I have so far. Any advice on how and what part of the following code can be changed to achieve this is greatly appreciated!

Current partially erroneous output examples:

JOAUZKKMJVNDFABILLKAWNWEKUEJGHKRCBDUYYRG

Enter character to be replaced: W

Modified string after replacement is: Θi.


AKNZPUWCCKNOIQADOYXZIVCGFUWTKRQOGSWSPFFS

Enter character to be replaced: FSQ

Modified string after replacement is: Θi.

Thank you very much for your time and guidance.

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


void getRandomStr();
void strreplace(char s1[], char chr, char repl_chr);

int main(int argc, const char argv[])
{


    char s1[41], s2, repl_chr;
    getRandomStr();
    printf("%c\n");

    gets(s1);
    printf("\nEnter character to be replaced: ");
    s2 = getchar();
    fflush(stdin);
    repl_chr = '*';
    printf("\nModified string after replacement is: ");
    strreplace(getRandomStr, s2, repl_chr);
    getch();
    return 0;



    return 0;
}


void getRandomStr(){


    char s1[41];
    int i;

    srand(time(NULL));

    for (i = 0; i < 40; i++){

        char c = rand() % 26 + 'A';

        s1[i] = c;

    }

    for (i = 0; i < 40; i++){

        putchar(s1[i]);

    }

}

void strreplace(char s1[], char chr, char repl_chr)
{
    int i = 0;
    while (s1[i] != '\0')
    {
          if (s1[i] == chr)
        {
          s1[i] = repl_chr;
        }
        i++;
    }
    puts(s1);
    return 0;
}




Aucun commentaire:

Enregistrer un commentaire