tags:

views:

144

answers:

3

I want codes for randomly selects the word (meaningful or meaningless) from 26 letters. The word contain 6 letters. I have the codes for C program or objective C, or you will give any idea to me.

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

/* Written by kaizer.se */
void randword(char *buf, size_t len)
{
  char alphabet[] = "abcdefghijklmnopqrstuvxyz";
  size_t i;

  for (i = 0; i < len; i++) {
    size_t idx = ((float)rand()/RAND_MAX) * (sizeof(alphabet) -1);
    buf[i] = alphabet[idx];
  }
  buf[len] = '\0';
}

int main(void) {
  char buf[1024];

  srand(time(NULL));

  randword(buf, 7);
  printf("Word: %s\n", buf);
  return 0;
}

Test:

$ ./rword 
Word: xoilfvv
kaizer.se
+4  A: 
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

main()
{
    srand(time(NULL));
    for (int i = 0; i < 6; ++i)
    {
        putchar('a' + (rand() % 26));
    }
    putchar('\n');
    return EXIT_SUCCESS;
}

Salt to taste.

Update0

It would seem the OP does not know how to compile the above. If saved into a file called so.c, compile it with make so CFLAGS=-std=c99 from the same folder.

Matt Joiner
thanks so much ..
heyram
A: 
const int string_length = 5;
char the_string[string_length + 1];
for(int i = 0; i <= string_length; i++)
     the_string[i] =  the_string[i] % 26+ 'a';
the_string[string_length] = 0;