3

The assignment asks to print out the number of times a chosen character appears in an input (no length limit) string. I wanted to solve it by only using do or do-while loops, and after a bit of googling I found this code (source: https://www.tutorialgateway.org/c-program-to-count-all-occurrence-of-a-character-in-a-string/.).
I get the gist of it, but there are many things I still haven't covered, such as the meaning of str[i], the meaning of the variable ch, and kind of how the structure works. How can I interpret it piece by piece? Or if there's any simpler way, how can I work on it? I'm a beginner and I fear this is much easier than expected but I don't have the base to move on, thank you

#include <stdio.h>
#include <string.h>
 
int main() {
    char str[10], ch;
    int i, Count;
    i = Count = 0;
 
    printf("\n Please Enter any String :  ");
    gets(str);
    
    printf("\n Please Enter the Character that you want to Search for :  ");
    scanf("%c", &ch);
    
    while (str[i] != '\0') {
        if (str[i] == ch) {
            Count++;
        }
        i++;
    }
    printf("\n The Total Number of times '%c' has Occurred = %d ", ch, Count);
    
    return 0;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189
cadou
  • 33
  • 3
  • 3
    For reasons you'll learn later, this is a terrible example program. For your own future benefit, never use `gets()`. It's a dangerous function. – codyne Dec 30 '22 at 18:50

2 Answers2

1

Well i am giving an easy example regarding that problem with a proper explanation. Hope you might understand.

  • char is a datatype which will accepts character type of variable. Here str[100] will be an array of length 100, where we will store our search example. ch is a character type variable where we will store the character for which we will find the concurrence.

  • i and count are integer variables where i will be loop variable and the count will keep count of the concurrence.

  • after taking the text string using puts function we are storing it in the str[100] array.

  • then we are taking the search letter and stored it in ch.

  • we are now running for loop from 0 to the length of the string we have given. strlen() function returning us the length.

  • now str[i] will search from i=0 to the length size of the string. each time loop will go forward one by one letter and compare the letter with the letter inside ch.

  • if match found then we will increase the count value.

after the ending of the loop count will be the result of the concurrency.

reference: Concurrency of a letter in a string

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

int main()
{
    char str[100], ch;
    int i, Count;
    Count = 0;

    printf("\n Please Enter any String :  ");
    gets(str);

    printf("\n Please Enter the Character that you want to Search for :  ");
    scanf("%c", &ch);

    for(i = 0; i <= strlen(str); i++)
    {
        if(str[i] == ch)  
        {
            Count++;
        }
    }
    printf("\n The Total Number of times '%c' has Occured = %d ", ch, Count);

    return 0;
}
  • 3
    Best to avoid answers with the obsolete [`gets()`](https://stackoverflow.com/q/1694036/2410359), even if OP uses it. – chux - Reinstate Monica Dec 30 '22 at 19:22
  • 1
    Rather than potentially recalculate the string length, simply test for the _null character_. Also, this answer's `for(i = 0; i <= strlen(str); i++)` iterates 1 more than OP's better `while (str[i] != '\0') {` – chux - Reinstate Monica Dec 30 '22 at 19:24
  • 2
    `i <= strlen(str)` is not recommended. `'\0'` should not be considered part of the string. The classic termination test is `str[i] != '\0'`. Furthermore,`gets()` should not be used for this or any coding problem. – chqrlie Dec 30 '22 at 19:25
  • thank you, this clarified some things – cadou Dec 30 '22 at 22:00
  • Well this was very much shortcut way to solve it. But for problem solving purpose its not recommended to use gets() or strlen() as @chux - Reinstate Monica and chqrlie said. you can create your own custom code to find length without strlrn() and store string without gets(). I am giving you two references where you will get idea to do that. – Sabbir Alam Pran Dec 31 '22 at 03:45
  • Now take a challenge, replace those using the way discussed in these references. [link](https://www.geeksforgeeks.org/taking-string-input-space-c-3-different-methods/), [link](https://www.programiz.com/c-programming/examples/string-length#:~:text=Calculate%20Length%20of%20String%20without%20Using%20strlen()%20Function&text=Here%2C%20using%20a%20for%20loop,stored%20in%20the%20i%20variable.) – Sabbir Alam Pran Dec 31 '22 at 03:45
0

The code has the following parts:

1)The header files: These contain predefined functions like scanf() which you use in your program

2)The main function: Here you are performing your character count. Usually, this function contains the driver code for the program

ch is a variable for the character you want to count in your string. You are taking this as input from the user using scanf()

str is the string you are performing your count operation in. It is also taken as input.

str[i] is used to denote the index i in the string. For example in "test", the index of 's' will be 2 as it is the 3rd character and your index starts from 0.

Final note: I recommend going through the basic syntax and usage of arrays if you do not know indexing. Also, as someone commented, do not use gets(). It causes security issues in programs as user can access stack values by giving malicious inputs containing format specifiers. Instead, use a scanf with proper format specifiers or use fgets() when accessing content from files.

Abyss
  • 31
  • 4
  • thank you, you cleared out the variables side. I also thought that gets() was a special command and not a bad version of scanf, thank you for explaining that too, it wasn't obvious – cadou Dec 30 '22 at 22:01