How to case-insensitively check if a character exists in a string with C

2 Answers

0 votes
#include <stdio.h>
#include <string.h>
#include <ctype.h>

char* strchr_i(const char* str, int ch) {
    ch = tolower((unsigned char)ch);

    while (*str && tolower((unsigned char)*str) != ch) str++;

    return ch == '\0' || *str != '\0' ? (char*)str : NULL;
}

int main()
{
    char str[] = "C Programming";
    char ch = 'p';

    if (strchr_i(str, 'p') != NULL) {
        puts("exist");
    }
    else {
        puts("not exist");
    }
}




/*
run:

exist

*/

 



answered Sep 27, 2022 by avibootz
0 votes
#include <stdio.h>
#include <ctype.h>   // for tolower()
#include <string.h>  // for strlen()

// Convert a character to lowercase
char to_lower(char c) {
    return (char)tolower((unsigned char)c);
}

// Check if a character exists in a string (case-insensitive)
int char_exists_ignore_case(const char *s, char target) {
    char target_lower = to_lower(target);

    // Loop through each character in the string
    for (size_t i = 0; i < strlen(s); i++) {
        if (to_lower(s[i]) == target_lower) {
            return 1; // found
        }
    }

    return 0; // not found
}

int main() {
    // Define the string we want to search in
    const char *s = "CLanguage";

    // Perform the case-insensitive check
    int exists = char_exists_ignore_case(s, 'c');

    // Print the raw boolean result (0 or 1)
    printf("%d\n", exists);

    // Conditional check
    if (exists) {
        printf("exists\n");
    } else {
        printf("not exists\n");
    }

    return 0;
}


/*
run:

1
exists

*/

 



answered 9 hours ago by avibootz
edited 5 hours ago by avibootz

Related questions

...