HomeSoftware EngineeringEasy methods to Decide if a String Solely Incorporates Distinctive Characters in...

Easy methods to Decide if a String Solely Incorporates Distinctive Characters in C


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-about completely different characters.

The answer in C

Possibility 1:

int has_unique_chars(const char *str) {
  int masks[128]={0};
  whereas (*str) if (++masks[*str++]>1) return 0;
  return 1;
}

Possibility 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;
}

Possibility 3:

#embrace <stdbool.h>
#embrace <string.h>
#embrace <stdio.h>

bool has_unique_chars(const char *str) {
  size_t len = strlen(str);
  char *listing = malloc(len);
  for (int i = 0; i < len; i++) {
    for (int z = 0; z < i; z++) {  
      if (*(listing + z) == str[i]) {
        return false;  
      }
    }
    *(listing + i) = str[i];
  }
  return true;
}

Take a look at instances to validate our resolution

#embrace <criterion/criterion.h>

bool has_unique_chars(const char *str);

Take a look at(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"));
}
RELATED ARTICLES

Most Popular

Recent Comments