Char compare Function in C -


there times when realy need compare 2 chars , know there no function in c compare 2 chars (maybe i'm wrong) , because of decided write 1 of own. function working fine i'm not sure if ok, or there problems. decided ask if function ok. here program:

#include<stdio.h> #include<string.h>  int chrcmp(const char chr1, const char chr2);  int main(void){     char firstchar = 'a';     char secondchar = 'a';      if( chrcmp( firstchar, secondchar ) == 0 ){         printf("we have match\n");     }else{         printf("there no match found.\n");         printf("%c",chrcmp(firstchar, secondchar));     }      return 0; }  int chrcmp(const char chr1, const char chr2){     size_t lenght1, lenght2;      char s1[2] = {chr1 , '\0'}; /* convert chr1 string */     char s2[2] = {chr2 , '\0'}; /* convert chr2 string */      lenght1 = strlen(s1); /* store lenght of first string */     lenght2 = strlen(s2); /* store lenght of second string */      if( lenght1 == 1 && lenght2 == 1){  /* checking if both strings have same size (1) */         if( strcmp(s1,s2) == 0 ){     /* compare both strings */             return 0; /* match found! */         }else{             return 1; /*no match!;*/         }     }else{         return 1; /*to many chars found!;*/     } } 

if there problems, or if did wrong have no ideeas.

in c, char integer type. arithmetical operations, promoted int, can use normal integer comparison.

note whether char signed or unsigned implementation defined, make sure, should use signed char or unsigned char (recommended) if arithmetics (includes comparisons) on chars other test equality.

what cannot compare 2 char arrays, such as

char ch[] = "hello"; if ( ch == "hello" )     ... 

for need strncmp() or strcmp(). use latter if absolutely sure both strings terminated!


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -