Skip to main content

Featured

Mastering Hollow Square Patterns in C: Stars, Numbers, Alphabets & Binary

πŸ”’ C Program to Print Hollow Continuous Number Square πŸ“„ Source Code: #include <stdio.h> int main() { int num, k = 0; printf("Enter the number:\n"); scanf("%d", &num); for(int i = 1; i <= num; i++) { for(int j = 1; j <= num; j++) { if(i == 1 || i == num || j == 1 || j == num) { // k increments sequentially only along the borders printf("%d ", k++); } else { printf(" "); } } printf("\n"); } return 0; } πŸ“‹ Copy Code πŸ’» Expected Output (Input: 5): Enter the number: 5 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 πŸ”’ C Program to Print Standard Hollow Binary Row Square πŸ“„ Source Code (Fixed Specifier): #include <stdio.h> int main() { ...

C program to implement a custom strstr() function to check if one string is a substring of another

Custom strstr() Function in C

πŸ”Ά Custom strstr() Function in C

#include <stdio.h>

// Custom strstr function
int my_strstr(char *str1, char *str2) {
    int i, j;
    for (i = 0; str1[i] != '\0'; i++) {
        for (j = 0; str2[j] != '\0'; j++) {
            if (str1[i + j] != str2[j]) {
                break;
            }
        }
        // If full substring matched
        if (str2[j] == '\0') {
            return 1;
        }
    }
    return 0;
}

int main() {
    char str1[100], str2[100];

    printf("Enter string1: ");
    scanf("%s", str1);

    printf("Enter string2: ");
    scanf("%s", str2);

    if (my_strstr(str1, str2)) {
        printf("String2 is a substring of string1\n");
    } else {
        printf("String2 is not a substring of string1\n");
    }

    return 0;
}
  

πŸ“˜ Explanation:

This C program defines a custom version of the strstr() function to check whether one string is a substring of another.

πŸ”Ή The outer loop goes through each character of the main string str1.
πŸ”Ή The inner loop checks if all characters of str2 match starting from current index in str1.
πŸ”Ή If all characters of str2 match (end of str2 is reached), the function returns 1 (true).
πŸ”Ή Otherwise, it continues to the next position.
πŸ”Ή If no match is found by the end of the loop, it returns 0 (false).

πŸ” Sample Output:

Enter string1: hello
Enter string2: ell
String2 is a substring of string1

Enter string1: openai
Enter string2: bot
String2 is not a substring of string1
    

🏷️ Keywords:

custom strstr in C, substring check program, string functions in C, how to check substring manually in C, C interview string question, nested loop string match

Comments

πŸŒ™