#include <stdio.h>/* Function returns number of times c occurs in a string */ int numTimes(const char *str, const char c){ int num=0; while(*str){ if(*str == c) num++; str++; } return num; } /* Checks for the presence of the character in res array to avoid duplication */ int isPresent(const char *arr, const char c){ while(*arr){ if(c == *arr) return 1; arr++; } return 0; } int main(){ char arr[20] = "AAABDDDFF"; char res[20]; char check; int num, i; int j=0; for(i=0;*(arr+i);i++){ check = arr[i]; if(isPresent(res, check)==0){ printf("check: %c\n", check); res[j++] = check; num = numTimes(arr, check); check = (char)((int)'0'+num); res[j++] = check; res[j] = '\0'; } } printf("%s\n",res); return 0; } // Output: A3B1D3F2
Thursday, 18 April 2013
Find the number of occurence of a character in a string and store it in another array.
Monday, 15 April 2013
STRCASECMP : Implementation in C
#include<stdio.h> int mytoupper(char c){ // 'A' = 65 // 'a' = 97 if(('a'<=c) && (c <= 'z')) c = 'A' + (c - 'a'); return c; } int mytolower(char c){ // 'A' = 65 // 'a' = 97 if(('A' <= c) && (c <= 'Z')) c = 'a' + (c - 'A'); return c; } int mystrcasecmp(const char *s1, const char *s2){ while((mytoupper(*s1)==mytoupper(*s2)) && *s1 && *s2) s1++, s2++; return *s1-*s2; } int main(){ char *a = "Umesh"; char b[] = "uMeSh"; int diff = mystrcasecmp(a,b); if(diff==0) printf("Equal\n"); else if(diff < 0) printf("Less than\n"); else printf("Greater\n"); return 0; } // Output: Equal
MEMSET Implementation in C
#include<stdio.h> void *mymemset(void *ptr, int value, size_t num){ size_t i; // Typecast to char so that pointer increment can be done as // void pointer can't be increment because compiler // does not know the size of "ptr" char *cPtr = ptr; for(i = 0; i<num; i++,cPtr++){ *cPtr = value; } return ptr; } int main(){ char a[]="Umesh is typing this line for testing mymemset"; mymemset(a,'0',10); printf("%s\n", a); return 0; }
STRSTR Implementation in C
const char * strstr ( const char * str1, const char * str2 );
char * strstr ( char * str1, const char * str2 );
Returns a pointer to the first occurrence of str2 in str1, or a
null pointer if str2 is not part of str1.
The matching process does not include the terminating
null-characters, but it stops there.
#include
char *mystrstr(const char *str1, const char *str2){
char *a, *b;
while(*str1){
a = str1;
b = str2;
while(*a && *b && (*a == *b)) a++, b++;
if(*b == '\0') return a;
str1++;
}
return NULL;
}
int main(){
char *a = "Andaman and Nicobar is a beautiful island";
char *b = "and ";
char *res = mystrstr(a,b);
if(res)
printf("%s\n", res);
else
printf("Substring not found\n");
return 0;
}
//Output: Nicobar is a beautiful island
Subscribe to:
Comments (Atom)