finding characters in string
#include <stdio.h>
int main() {
char str[] = "Hello, world!";
char target = 'o';
int count = 0;
for (int i = 0; str[i] != '\0'; i++) {
if (str[i] == target) {
count++;
}
}
printf("The character '%c' appears %d times in the string.\n", target, count);
return 0;
}
Explanation:
Include Header File: The
#include <stdio.h>
directive is used to include the standard input-output header file in the program.Main Function: The
main()
function is the entry point of the program execution.Declare Variables:
char str[] = "Hello, world!";
declares and initializes a character arraystr
containing the string "Hello, world!".char target = 'o';
declares a character variabletarget
and assigns the value'o'
to it.int count = 0;
initializes an integer variablecount
to store the count of occurrences of the target character.For Loop:
for (int i = 0; str[i] != '\0'; i++)
initializesi
to 0 and iterates through the stringstr
until it encounters the null character ('\0'
) denoting the end of the string.Inside the loop:
if (str[i] == target)
checks if the current character in the string (str[i]
) is equal to the target character ('o'
in this case).- If true,
count
is incremented by 1 usingcount++
.
Print Result:
printf("The character '%c' appears %d times in the string.\n", target, count);
prints the count of occurrences of the target character.Return: The
return 0;
statement signifies the successful execution of the program, and0
is returned to the operating system to indicate this. ```