0

Suppose we have a string called StringA[] = "ABCD". you have to delete only one char and make new strings like "BCD, ACD,ABD,ABC". is this case you need to determine how many time the strings appears in a other string StringB[]; the length of StringA is allways less than StringB's but they both needs to have a length of less than 100 and bigger than 2

Following is my attempt. I make a pointer so save the value of S and then do operations on it and when one iteration is done I reassign it to S again. but the solution it provides is wrong. for instance for the case above the type2 variable needs to be 4 but it gives 1. I guess the problem is in using memmove function. I would appreciate any help.

#include <stdio.h>
#include <string.h>



int CheckOccurence(size_t len, char* stringA, char* stringB);
int type1, type2, type3;


int main(int argc, char **argv)
{

char L[100];
char S[100];
char *holdChar;

while(scanf("%s%s", S,L) == 2){

    size_t lenS = strlen(S);
    size_t lenL = strlen(L);

    int minLengthSat = (lenS >= 2 && lenL >= 2);
    int maxLengthSat = (lenS <= 100 && lenL <= 100);
    int isSless = lenS <= lenL; 

    holdChar = S;
    if(minLengthSat && maxLengthSat && isSless){

        type1 = CheckOccurence(lenS,&S,&L);


        for (int i =0; holdChar[i] !='\0'; i++ ){
            //holdChar[i] = holdChar[i+1];
            memmove(&holdChar[i], &holdChar[i+1], strlen(holdChar) -i);
            type2 += CheckOccurence(lenS,holdChar,&L);
            holdChar = S;
        }

        printf("%d%d\n",type1,type2);
        printf("%s\n",S);

    }else{
        printf("Condition not fulfilled. Try again!\n");
    }

}


return 0;
 }

int CheckOccurence(size_t len, char* stringA, char* stringB){

int count = 0;
while(stringB = strstr(stringB, stringA))
{
   count++;
   stringB+=len;
}
return count;

}
Payam30
  • 689
  • 1
  • 5
  • 20
  • It looks like you are not moving enough chars. Make sure to move all the remain chars + the null terminator. `memmove` operates as if there's an intermediate buffer to hold the moved bytes, so that's not likely an issue. – bruceg Aug 02 '18 at 01:19
  • Could you provide a better example, what you actually want to achieve? Currently I don't understand why you're modifying **S** at all. Also your `scanf` is terribly **unsafe**. Use `scanf("%99s%99s")` to check for bounds. Also you're trying to pass `char (*)[100]` (Pointer to an Array of char of size 100)[see](http://c-faq.com/aryptr/ptrtoarray.html), use `L` or `&L[0]` instead. Your `CheckOccurence` seems correct, except the spelling error. – Inrin Aug 02 '18 at 21:33

0 Answers0