Check Character Presence in a String in C

This C code snippet defines a function to check if a specific character is present in a given string. The main function tests the character 'w' in the string 'hello world' and prints whether the character is found or not. It's a simple demonstration of string manipulation and function usage in C.
mail@pastecode.io avatar
unknown
c_cpp
a month ago
503 B
3
Indexable
Never
#include <stdio.h>

int is_present(char str[], char ch) {
    for (int i = 0; str[i] != '\0'; i++) {
        if (str[i] == ch) {
            return 1; // Character is found
        }
    }
    return 0; // Character not found
}

int main() {
    char str[] = "hello world";
    char ch = 'w';
    
    if (is_present(str, ch)) {
        printf("Character '%c' is present in the string\n", ch);
    } else {
        printf("Character '%c' is not present in the string\n", ch);
    }
    
    return 0;
}
Leave a Comment