How to check if a string contains only unique characters in C

2 Answers

0 votes
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
   
int compare_function(const void *a, const void *b) {
   return ( *(char*)a - *(char*)b );
}
bool contains_unique_chars(char *s) { 
	int len = strlen(s);
    qsort(s, len, sizeof(char), compare_function);
    
    for (int i = 0; i < len; i++) { 
        if (s[i] == s[i + 1]) { 
            return false; 
        } 
    } 
    return true; 
} 
        
int main() 
{                       
    char s[] = "abcde";
    
    if (contains_unique_chars(s)) { 
        puts("yes");
    } 
    else { 
        puts("no");
    } 
                  
    return 0; 
} 
           
           
           
/*
run:
           
yes
           
*/

 

 



answered Dec 28, 2019 by avibootz
edited Dec 31, 2019 by avibootz
0 votes
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
    
int compare_function(const void *a, const void *b) {
   return ( *(char*)a - *(char*)b );
}
bool contains_unique_chars(char *s) { 
    char *tmp = strdup(s);
    bool b = true;
	int len =  strlen(tmp); 
     
    qsort(tmp, len, sizeof(char), compare_function);
    
    for (int i = 0; i < len; i++) { 
        if (tmp[i] == tmp[i + 1]) { 
            b = false;
        } 
    } 
    free(tmp);
     
    return b; 
} 
         
int main() 
{                       
    char s[] = "abcde";
         
    if (contains_unique_chars(s)) { 
        puts("yes");
    } 
    else { 
        puts("no");
    }
                  
    return 0; 
} 
            
            
            
/*
run:
            
yes
            
*/

 



answered Dec 30, 2019 by avibootz
edited Dec 31, 2019 by avibootz

Related questions

1 answer 169 views
1 answer 176 views
2 answers 281 views
1 answer 169 views
2 answers 206 views
4 answers 288 views
...