How to check whether two strings contain same characters in C

2 Answers

0 votes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
int compare_function(const void *a, const void *b) {
   return ( *(char*)a - *(char*)b );
}
int main() {
    char s1[32] = "c programming";
    char s2[32] = "progingramm c";
                 
    qsort(s1, strlen(s1), sizeof(char), compare_function);
	qsort(s2, strlen(s2), sizeof(char), compare_function);
	
	if (strcmp(s1, s2) == 0)
		puts("yes");
	else
		puts("no");
     
    return 0;
}
 
  
  
/*
run:
  
yes
 
*/

 



answered Oct 26, 2019 by avibootz
0 votes
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
    
void remove_duplicates(char *s) {
  for (int i = 0; i < strlen(s); i++) {
        for (int j = i + 1; s[j] != '\0'; j++) {
            if (s[j] == s[i]) {
                for (int k = j; s[k] != '\0'; k++) {
                    s[k] = s[k + 1];
                }
                j--;
            }
        }
    }
}

int compare_function(const void *a, const void *b) {
    return ( *(char*)a - *(char*)b );
}
 
bool contain_same_charactersr(char s1[], char s2[]) {
	char *s1_tmp = (char *)malloc((strlen(s1) * sizeof(char)) + 1);
    char *s2_tmp = (char *)malloc((strlen(s2) * sizeof(char)) + 1);
     
    strcpy(s1_tmp, s1);
    strcpy(s2_tmp, s2);
	
	remove_duplicates(s1_tmp);
    remove_duplicates(s2_tmp);
	
	qsort(s1_tmp, strlen(s1_tmp), sizeof(char), compare_function);
    qsort(s2_tmp, strlen(s2_tmp), sizeof(char), compare_function);
	
	int b = false;
	if (strcmp(s1_tmp, s2_tmp) == 0)
		b = true;
		
	free(s1_tmp);
	free(s2_tmp);
	
	return b;
}

 
int main() {
    char s1[] = "c programming";
    char s2[] = "ggggproooogrammin cccc";
      
    if (contain_same_charactersr(s1, s2))
        puts("yes");
    else
        puts("no");
}
   
   
    
/*
run:
    
yes
   
*/

 



answered Oct 27, 2019 by avibootz
edited Oct 29, 2019 by avibootz
...