The problem
Write a program to find out if a string incorporates solely distinctive characters. Return true if it does and false in any other case.
The string might comprise any of the 128 ASCII characters. Characters are case-sensitive, e.g. ‘a’ and ‘A’ are thought of totally different characters.
The answer in C
Choice 1:
int has_unique_chars(const char *str) {
int masks[128]={0};
whereas (*str) if (++masks[*str++]>1) return 0;
return 1;
}
Choice 2:
#embrace <limits.h>
_Bool has_unique_chars(const char *str) {
char hit[CHAR_MAX + 1] = {0};
whereas (*str) {
if (*str < 0) { str++; proceed; }
if (hit[*str]) return 0;
hit[*str++] = 1;
}
return 1;
}
Choice 3:
#embrace <stdbool.h>
#embrace <string.h>
#embrace <stdio.h>
bool has_unique_chars(const char *str) {
size_t len = strlen(str);
char *checklist = malloc(len);
for (int i = 0; i < len; i++) {
for (int z = 0; z < i; z++) {
if (*(checklist + z) == str[i]) {
return false;
}
}
*(checklist + i) = str[i];
}
return true;
}
Check circumstances to validate our resolution
#embrace <criterion/criterion.h>
bool has_unique_chars(const char *str);
Check(has_unique_chars, test_example) {
cr_assert_not(has_unique_chars(" nAa"));
cr_assert(has_unique_chars("abcde"));
cr_assert_not(has_unique_chars("++-"));
cr_assert(has_unique_chars("AaBbC"));
}