The problem
Directions
Write a operate that takes a single string (phrase
) as argument. The operate should return an ordered listing containing the indexes of all capital letters within the string.
Instance
Take a look at.assertSimilar( capitals('CodEStAr'), [0,3,4,6] );
The answer in C
Possibility 1:
#embody <stddef.h>
#embody <string.h>
#embody <stdlib.h>
size_t *find_capitals(const char *phrase, size_t *nb_uppercase)
{
size_t n = strlen(phrase);
size_t *arr = (size_t *) calloc(n, sizeof(size_t));
size_t j = 0;
for(size_t i=0; i<n; i++) {
if(phrase[i] >='A' && phrase[i] <='Z') {
arr[j++] = i;
}
}
*nb_uppercase = j;
return realloc(arr, j * sizeof(size_t));
}
Possibility 2:
#embody <stddef.h>
#embody <stdlib.h>
#embody <string.h>
size_t *find_capitals (const char *phrase, size_t *nb_uppercase)
{
if (!phrase || !*phrase) {
*nb_uppercase = 0;
return 0;
}
*nb_uppercase = 0;
for (char const *itr = phrase; *itr; itr++)
if (*itr >= 'A' && *itr <= 'Z')
(*nb_uppercase)++;
size_t * const buffer = malloc(*nb_uppercase * sizeof(size_t));
for (size_t i = 0, j = 0; phrase[i]; i++)
if (phrase[i] >= 'A' && phrase[i] <= 'Z')
buffer[j++] = i;
return buffer;
}
Possibility 3:
#embody <stddef.h>
size_t *find_capitals (const char *phrase, size_t *nb_uppercase)
{
size_t* arr = malloc(50 * sizeof(int));
int i = 0;
int a = 0;
whereas(phrase[i] != ' '){
if(phrase[i] >= 'A' && phrase[i] <= 'Z'){
arr[a] = i;
a++;
}
i++;
}
*nb_uppercase = a;
return arr;
return NULL;
}
Take a look at circumstances to validate our answer
#embody <time.h>
#embody <stdlib.h>
#embody <criterion/criterion.h>
extern void do_test (const char *phrase, size_t exp_len, const size_t anticipated[exp_len]);
#outline ARR_LEN(array) (sizeof(array) / sizeof *(array))
#outline sample_test(phrase, anticipated) do_test(phrase, ARR_LEN(anticipated), anticipated)
Take a look at(tests_suite, sample_tests)
{
do_test("", 0, NULL);
do_test("4ysdf4", 0, NULL);
sample_test("CodEStAr", ((const size_t[]){0, 3, 4, 6}));
sample_test("aAbB", ((const size_t[]){1, 3}));
sample_test("ABCDEF", ((const size_t[]){0, 1, 2, 3, 4, 5}));
}
enum { MAX_LEN = 40 };
#outline take_char(str) ((str)[rand() % (sizeof(str) - 1)])
// generates a random phrase, fill the indexes[] array, return the variety of uppercase letters
static size_t random_word (char *phrase, size_t uppercase_indexes[])
{
size_t size = 1 + (rand() % MAX_LEN);
size_t idx_caps = 0;
for (size_t i = 0; i < size; i++) {
swap (rand() % 3) {
case 0:
phrase[i] = take_char("abcdefghijklmnopqrstuvwxyz");
break;
case 1:
phrase[i] = take_char("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
uppercase_indexes[idx_caps++] = i;
break;
default:
phrase[i] = take_char("@&~#0123456789-*/=,;:!.");
break;
}
}
phrase[length] = ' ';
return idx_caps;
}
Take a look at(tests_suite, random_tests)
{
srand(time(NULL));
size_t anticipated[MAX_LEN];
char phrase[MAX_LEN + 1];
for (int i = 0; i < 100; i++) {
size_t exp_len = random_word(phrase, anticipated);
do_test(phrase, exp_len, anticipated);
}
}