🔍 Find First Occurrence of Character in String in C (With and Without Function)

⬅️ Back

🔍 Find First Occurrence of a Character in a String in C (With and Without Function)

This tutorial shows two ways to find the first occurrence of a character in a string in C:

  • ✅ Using a custom function with strchr()
  • 🛠️ Without using a separate function (all code in main())

✅ Method 1: With Function (Using strchr())

#include <stdio.h>
#include <string.h>

int findFirstOccurrence(char *str, char ch) {
    char *pos = strchr(str, ch);
    if (pos != NULL) {
        return (int)(pos - str);  // zero-based index
    } else {
        return -1; // not found
    }
}

int main() {
    char str[100], ch;
    int index;

    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);

    // Remove newline from fgets
    int len = strlen(str);
    if (len > 0 && str[len - 1] == '\n') {
        str[len - 1] = '\0';
    }

    printf("Enter the character to find: ");
    scanf("%c", &ch);

    index = findFirstOccurrence(str, ch);

    if (index != -1) {
        printf("Character '%c' found at position: %d\n", ch, index + 1);
    } else {
        printf("Character '%c' not found in the string.\n", ch);
    }

    return 0;
}

📝 Explanation:

  • findFirstOccurrence() uses strchr() to find the character pointer.
  • Returns the zero-based index or -1 if not found.
  • main() handles input and output.

🛠️ Method 2: Without Function (All Logic Inside main())

#include <stdio.h>
#include <string.h&gt>

int main() {
    char str[100], ch;
    char *pos;

    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);

    int len = strlen(str);
    if (len > 0 && str[len - 1] == '\n') {
        str[len - 1] = '\0';
    }

    printf("Enter the character to find: ");
    scanf("%c", &ch);

    pos = strchr(str, ch);

    if (pos != NULL) {
        printf("Character '%c' found at position: %ld\n", ch, pos - str + 1);
    } else {
        printf("Character '%c' not found in the string.\n", ch);
    }

    return 0;
}

📝 Explanation:

  • Uses strchr() directly inside main().
  • Finds and prints the first occurrence position or shows not found.

📌 Summary

Finding the first occurrence of a character in a string is straightforward with strchr(). You can wrap the logic inside a function or keep it in main() depending on your preference.

strchr in c, find character in string, first occurrence of char in c, strchr example, c programming string functions, search character in string c, custom strchr function

āĻ•োāύ āĻŽāύ্āϤāĻŦ্āϝ āύেāχ:

āĻāĻ•āϟি āĻŽāύ্āϤāĻŦ্āϝ āĻĒোāϏ্āϟ āĻ•āϰুāύ