SHARE
TWEET

String counter

a guest Jun 24th, 2019 96 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <string.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #define MAX 100
  5.  
  6. int strcount(char* strA, char* strB);
  7. int doubleCheck(char* strA, char* strB);
  8.  
  9. int main(void)
  10. {
  11.   char*A = (char*)malloc(sizeof(char)*100);
  12.   char*B = (char*)malloc(sizeof(char)*10);
  13.     for(int i = 0; i < MAX; i++)
  14.     {
  15.       A[i] ='\0';
  16.     }
  17.   if(malloc == NULL)
  18.   {
  19.     printf("Error allocating memory");
  20.     exit(1);
  21.   }
  22.  
  23.   //A = "The friends of Ringo Ishikawa";
  24.   //char*B = "Ringo Ishikawa";
  25.   printf("Please enter your first string.");
  26.   fgets(A, MAX, stdin);
  27.   printf("Please enter your second string.");
  28.   fgets(B, MAX, stdin);
  29.   strcount(A, B);
  30.  
  31.   free(A);
  32.   free(B);
  33.   return 0;
  34. }
  35.  
  36. int strcount(char* strA, char* strB)
  37. {
  38.   int count = 0;
  39.   char* ptr;
  40.   char* loc = malloc(sizeof(char*)*100);
  41.   char*A = ptr;
  42.   char*B = strB;
  43.  
  44.   for(ptr = strA; *ptr!= '\0'; *(ptr++))
  45.   {
  46.     if((loc=strstr(ptr, strB)) != NULL)
  47.     {
  48.       if(*ptr == *strB)
  49.       {
  50.         if(doubleCheck(ptr, strB) == 1)
  51.             count++;
  52.       }
  53.     }
  54.   }
  55.   printf("\nThe amount of times that %s appears in %s is %d", strB, strA, count);
  56.   free(loc);
  57. }
  58.  
  59. int doubleCheck(char* strA, char* strB)
  60. {
  61.   int ccount = 0;
  62.   printf("\nThe strings being compared are %s and %s", strA, strB);
  63.  
  64.   for(int i = 0; i < strlen(strB); i++)
  65.   {
  66.     if(strA[i] == strB[i]){
  67.       ccount++;
  68.     }else
  69.       break;
  70.   }
  71.   if(ccount == strlen(strB))
  72.     return 1;
  73.   else
  74.     return 0;
  75. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top