đ 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()
usesstrchr()
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>>
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 insidemain()
. - 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.
āĻোāύ āĻŽāύ্āϤāĻŦ্āϝ āύেāĻ:
āĻāĻāĻি āĻŽāύ্āϤāĻŦ্āϝ āĻĒোāϏ্āĻ āĻāϰুāύ