Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a function to accept a string (pointer to a char) and a char. The function

ID: 3623609 • Letter: W

Question

Write a function to accept a string (pointer to a char) and a char. The function should count and return the number of times the character appears in the string. For instance, if the string was HAPPINESS IS PROGRAMMING and the character was P then P occurs 3 times and the function should return a 3.



Here is my code: I am having problem at passing the count back, it seems like the while loop isn't working. Something is wrong with the *target.

#include

#include

int check(char* pstr, char* target);



int main ()

{



char str[] = "THIS IS A SAMPLE.";

char* pstr = str;

char target;

int count;



count = check(str, &target);

printf(" %c appears %d times in the string. ", target, count);

return 0;

}



int check(char* pstr, char* target)

{



char tAdr;

int count =0;



printf("Enter the character that want to be search: ");

scanf(" %c", target);

printf ("Looking for the '%c' character in *%s*... ", *target, pstr);



tAdr = strchr(pstr, target);



while(tAdr)

{

count++;

tAdr =strchr(tAdr+1, target);

}



return count;

}

Explanation / Answer

// use this simplfied code dude :)

#include<stdio.h>
#include<string.h>
int countOfSubString(char* sentence, char* substring)
{

    int lens = strlen(substring);
    int lenx = strlen(sentence);
    int count = 0;
    int j = 0,i;
    for(i = 0; i < (lenx-lens+1); ++i) {
        for(j = 0; j < lens; ++j) {
            if(sentence[i+j] != substring[j]) {
                break;
            }
        }
        if(j==lens)
        {
             count++;
        }
    }
    return count;
}
int main()
{

int count = countOfSubString("HAPPINESS IS PROGRAMMING","P");
printf(" %d times in the string. ", count);

return 0;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote