Home > Mobile >  Function is telling me the length of the string and not the number of occurrences of the char inputt
Function is telling me the length of the string and not the number of occurrences of the char inputt

Time:01-04

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

int countLetters(char *string1, char letter){   
    int count=0;

    for(int i=0; i<strlen(string1); i  ){
        if(string1[i]=letter){
        count  ;
        }
    }    
    return count;
}

int main(){
    char string1[200];
    char letter;
    int count;

    printf("\nEnter the string: \n");
    fgets(string1, 200, stdin);

    printf("\nEnter character to be searched: \n");
    scanf("%c", &letter);
    
    count = countLetters(string1, letter);

    printf("\nThe number of occurrences: %d", count);
}

I was expecting for the function to output the number of times each letter of the array was equal to the char(letter) inputted by the user, but it is just giving me the length of the string.

CodePudding user response:

Change the line:

    if(string1[i]=letter){

to

    if(string1[i]==letter){

Note, that the string1[i]=letter was overwriting data in string1[i].

CodePudding user response:

You have to use equal equal to operator instead of assignment operator in if condition like this

if(string1==latter)

in your if condition if(string1=latter) value of latter variable is assign to string1[i]

  • Related