โœฆ

Anna Grigoryan

ENGS110 ยท Spring 2026
โ† Back to main page
๐Ÿ“ Strings
๐Ÿ“„
ex7 .c โ–ถ
#include <stdio.h>
// problem 7 from practice exercises (strings)
int main() {
    const char* str = "LOREM IPSUM DOLOR SIT AMET CONSECTETUER ADIPISCING";
    int count[26] = {0};  // index 0 = A, index 1 = B, until index 25 = Z
    for (int i = 0; str[i] != '\0'; i++) {
        if (str[i] >= 'A' && str[i] <= 'Z') {
            count[str[i] - 'A']++;  // 'A'-'A'=0, 'B'-'A'=1, 'C'-'A'=2 and so on
        }
    }
    for (int i = 0; i < 26; i++) {
        if (count[i] > 0) {
            printf("%c: %d\n", 'A' + i, count[i]);
        }
    }
    return 0;
}
๐Ÿ“„
substring .c โ–ถ
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
//exercise 28 from practices
int main(void) {
    char main_str[100];
    char sub_str[100];
    bool found = false;
    //read strings
    printf("enter main string: ");
    scanf("%s", main_str);
    printf("enter substring to find: ");
    scanf("%s", sub_str);
    int main_len = strlen(main_str);
    int sub_len = strlen(sub_str);
    //use sliding window pattern
    //we only need to check up to main_len - sub_len positions
    for (int i = 0; i <= main_len - sub_len; i++) {
        bool match = true;
        //check if substring matches at position i
        for (int j = 0; j < sub_len; j++) {
            if (main_str[i + j] != sub_str[j]) {
                match = false;
                break;  //early exit
            }
        }
        if (match) {
            found = true;
            break;
        }
    }
    printf("%s is %sa substring\n", sub_str, found ? "" : "NOT ");
    return 0;
}