Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I would like to generate a random string of only lower-case ASCII characters (meaning lower case letters, numbers, and other ASCII characters; just no upper-case lettesr).
The max length of the string should be 587 characters (including null terminator).
How would I go about doing this?
Thanks
#define N 588
#include <stdlib.h>
#include <time.h>
void gen(char *dst)
{
int i, n;
srand(time(NULL)); /* init seed */
if ((dst = malloc(N)) == NULL) /* caller will need to free this */
return;
for (i = 0; i < N; )
if ((n = rand()) < 'A' && n > 'Z')
dst[i++] = n;
dst[N - 1] = 0; /* null terminate the string */
}
I tried this:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <ctype.h>
#define BUFFER_SIZE 587 /* 587 including NULL so 0..585 and 586 is NULL */
int main(int argc, char** argv)
{
size_t i;
char buffer[BUFFER_SIZE];
int x;
srand((unsigned int)time(NULL));
memset(buffer, 0, sizeof(buffer));
for (i = 0; i < BUFFER_SIZE-1; i++)
{
/* Note: islower returns only a b c..x y z, isdigit 0..9 and isprint only printable characters */
do
{
x = rand() % 128 + 0; /* ASCII 0 to 127 */
}
while (!islower(x) && !isdigit(x) && !isprint(x));
buffer[i] = (char)x;
}
buffer[BUFFER_SIZE-1] = '\0';
printf("%s", buffer);
getchar();
return EXIT_SUCCESS;
}
This way you can do a random string with whatever characters you want. The only thing is you should put them in the function
#include <stdlib.h>
void gen_random(char *s, const int len) {
static const char alphanum[] =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < len; ++i) {
s[i] = alphanum[rand() % (sizeof(alphanum) - 1)];
}
s[len] = 0;
}
Related
The code seems to only count one of the occurances when using scanf() or a defined getChar() I have set up but will count all and display when the string is defined in code. How can I get the output to work correctly while having a user input.
I've tried a few different approaches at taking the user input as seen but still I don't seem to be getting the result desired.
//#define _CRT_SECURE_NO_WARNINGS
#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
int main() {
char *s;
fgets(&s[0],98,stdin);
int letter_counts[26] = {0};
int length = strlen(s);
char c;
for (int i = 0; i < length; i++) {
c = toupper(s[i]);
if (c >= 'A' && c <= 'Z')
letter_counts[c - 'A']++;
}
for (int i = 0; i < 26; i++) {
if (letter_counts[i] > 0) {
printf("%c%d ", 'A' + i, letter_counts[i]);
}
}
return 0;
}
I've Now changed it to use the fgets() but I don't seem to be using that correctly either...
Your main problem is that you don't allocate any space to s. Also introduces a couple of constants instead of your magic values for size:
#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#define ALPHA_LEN 'Z' -'A' + 1
#define STR_LEN 98
int main() {
char s[STR_LEN+1];
if(!fgets(&s[0],STR_LEN+1, stdin)) {
printf("gets failed\n");
return 1;
}
int letter_counts[ALPHA_LEN] = {0};
size_t length = strlen(s);
for (size_t i = 0; i < length; i++) {
char c = toupper(s[i]);
if (isupper(c))
letter_counts[c - 'A']++;
}
for (size_t i = 0; i < sizeof letter_counts / sizeof *letter_counts; i++) {
if (letter_counts[i]) {
printf("%c%d ", 'A' + i, letter_counts[i]);
}
}
printf("\n");
}
I need to get the length of the palindrome of the word in a string. Ex. tomyot length =2.
I wrote the following code but it doesn't work.
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
char str[20] = "tomyot";
char rstr[20];
strcpy(rstr, str);
strrev(rstr);
int i,j;
int count = 0;
int s=0;
for(i=0;i<strlen(str); i++){
for(j=s;j<strlen(str); j++){
if(str[i] == rstr[j]){
count+=1;
s = j+1;
continue;
}
}
}
printf("%d",count);
return 0;
}
Replace
sizeof(str)
with
strlen(str)
The former one returns the size of the str array which is 20 and the latter one returns the length of the contents of str which is 6.
I have made the changes and put comments in the code in /* .. */ blocks:
#include <stdio.h>
#include <string.h>
int main(void) {
/*
- You don't need to compute the reverse of the string, the input string itself will do your work.
- strrev() is not supported in GCC, so don't use it. See https://stackoverflow.com/a/8534275/4688321
for alternative implementation
*/
char str[20] = "tomyot";
int len_str = strlen(str);
int i, j, cnt = 0;
/*
- You don't need two nested for loops, one loop with two pointers:
first from the start of string and other from end of the string will do
- Just compare the ith character (from start) with the jth character (from end)
- Stop wherever i and j cross each other i.e. when i > j
*/
for (i = 0, j = len_str - 1; i <= j && i < len_str - 1; i++, j--) {
if (str[i] == str[j]) {
cnt++;
}
else break;
}
printf("%d\n", cnt);
return 0;
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I got string containing numbers separated by spaces. Numbers can be single-digit, two-digit, or perhaps more-digit. Check the example.
"* SEARCH 2 4 5 12 34 123 207"
I don't know how long the string is (how many numbers it contains), so I cant initiate the array properly. The result should look like this:
array = {2,4,5,12,34,123,207}
Do you have any ideas how to perform this?
like this:
#include <stdio.h>
#include <stdlib.h>
int main(void){
char *input = "* SEARCH 2 4 5 12 34 123 207";
int len = 0;
sscanf(input, "%*[^0-9]%n", &len);//count not-digits(The Number isn't negative)
char *p = input + len;
char *start = p;
int v, n = 0;
while(1 == sscanf(p, "%d%n", &v, &len)){
++n;//count elements
p += len;
}
int array[n];//or allocate by malloc(and free)
char *endp = NULL;
int i;
for(i = 0; i < n; ++i){
array[i] = strtol(start, &endp, 10);
start = endp + 1;
}
//check print
for(i = 0; i < n; ++i)
printf("%d ", array[i]);
puts("");
return 0;
}
You can try this approach. It uses a temporary buffer to hold the current integer that is being processed. It also uses dynamic arrays, to deal with different lengths of the string you want to process, and expands them when necessary. Although using strtok Would be better in this situation.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int
main(int argc, char *argv[]) {
char message[] = "* SEARCH 2 4 5 12 34 123 207";
char *buffer = NULL;
int *integers = NULL;
int buff_size = 1, buff_len = 0;
int int_size = 1, int_len = 0;
int ch, messlen, i, first_int = 0;
/* creating space for dynamic arrays */
buffer = malloc((buff_size+1) * sizeof(*buffer));
integers = malloc(int_size * sizeof(*integers));
/* Checking if mallocs were successful */
if (buffer == NULL || integers == NULL) {
fprintf(stderr, "Malloc problem, please check\n");
exit(EXIT_FAILURE);
}
messlen = strlen(message);
/* going over each character in string */
for (ch = 0; ch < messlen; ch++) {
/* checking for first digit that is read */
if (isdigit(message[ch])) {
first_int = 1;
/* found, but is there space available? */
if (buff_size == buff_len) {
buff_size++;
buffer = realloc(buffer, (2*buff_size) * sizeof(*buffer));
}
buffer[buff_len++] = message[ch];
buffer[buff_len] = '\0';
}
/* checking for first space after first integer read */
if (isspace(message[ch]) && first_int == 1) {
if (int_size == int_len) {
int_size++;
integers = realloc(integers, (2*int_size) * sizeof(*integers));
}
integers[int_len] = atoi(buffer);
int_len++;
/* reset for next integer */
buff_size = 1;
buff_len = 0;
first_int = 0;
}
/* for last integer found */
if (isdigit(message[ch]) && ch == messlen-1) {
integers[int_len] = atoi(buffer);
int_len++;
}
}
printf("Your string: %s\n", message);
printf("\nYour integer array:\n");
for (i = 0; i < int_len; i++) {
printf("%d ", integers[i]);
}
/* Being careful and always free at the end */
/* Always a good idea */
free(integers);
free(buffer);
return 0;
}
You can read each character and verify if it is in range of >=48(Ascii of 0) and less than = 57(Ascii of 9). If so is the case read them into a array Otherwise you could copy them to a temporary string and convert to int using functions like atoi()
#include <stdio.h>
int main(int argc, char *argv[])
{
int j=0,k,res;
char buff[10];
while(str[j])
{
if((str[j]>='0')&&(str[j]<='9'))
{
k=0;
while((str[j]!=' ')&&(str[j]!='\0'))
{
buff[k]=str[j++];
k++;
}
buff[k]=0;
res=atoi(buff);
//Store this result to an array
}
j++;
}
return 0;
}
I have a problem generating a random string in a function.
In the code below I have used ASCII characters from 65 to 90. I want to include 48 to 57, skipping 58 to 64.
Is there any way to do this?
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
int main()
{
char s[30];
random_string(s, 6,65,90);
printf("\n%s\n", s);
return 0;
}
void random_string(char * string, unsigned length,int min,int max)
{
/* Seed number for rand() */
srand((unsigned int) time(0) + getpid());
/* ASCII characters 33 to 126 */
unsigned int num_chars = length - 1;
unsigned int i;
for (i = 0; i < num_chars; ++i)
{
string[i] = rand() % (max - min + 1) + min;
}
string[num_chars] = '\0';
}
How about this?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char* wanted = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
void random_string(char* target, unsigned len, const char* sample, unsigned slen) {
while(len) {
*target = sample[rand() % slen];
++target, --len;
}
*target = '\0';
}
int main() {
char rnd_str[21];
//srand(...)
random_string(rnd_str, 20, wanted, strlen(wanted));
printf("%s\n", rnd_str);
}
I think that simplest way to achieve that is to reroll rand() if you have got number in unwanted range. To specify desired range, you can use bitmask or bool array instead of min/max.
It will look something like this:
do { c = rand() % 256; } while (!desired[c]);
string[i] = c;
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Can anyone give me a complete example of how to generate an Alphanumeric String randomly
like (ARG534UJ6) using C ? I'm completely new to C.
void gen_random(char *s, const int len) {
static const char alphanum[] =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < len; ++i) {
s[i] = alphanum[rand() % (sizeof(alphanum) - 1)];
}
s[len] = 0;
}
This is not working.
As pointed out by #IngoLeonhardt, use % (sizeof(alphanum) - 1) instead of % sizeof(alphanum)
My guess is that you don't have room for your string, try:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void gen_random(char *s, const int len) {
static const char alphanum[] =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < len; ++i) {
s[i] = alphanum[rand() % (sizeof(alphanum) - 1)];
}
s[len] = 0;
}
int main(void)
{
char *str = malloc(8 + 1);
/* initialize random seed: */
srand(time(NULL));
gen_random(str, 8);
printf("%s\n", str);
free(str);
return 0;
}