Find a Character from a Given String in C Programming

Introduction

In this tutorial, you’ll learn how to find a character from a given string using a simple C program. This is a common task in string manipulation where you need to search for a specific character within a string entered by the user. Understanding this helps you build foundational string handling skills in C programming.


C Program to Find a Character from a Given String

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

int main() {
char str[100], ch;
int found = 0;

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

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

for (int i = 0; str[i] != '\0'; i++) {
if (str[i] == ch) {
printf("Character '%c' found at position %d\n", ch, i + 1);
found = 1;
break;
}
}

if (!found) {
printf("Character '%c' not found in the string.\n", ch);
}

return 0;
}

Explanation

  • fgets() is used to read the entire string including spaces.
  • The loop iterates through each character of the string.
  • If the target character matches, the index is printed.
  • If the loop completes without finding the character, a not found message is displayed.

Output Example

Enter a string: OpenAI GPT model
Enter the character to find: G
Character 'G' found at position 8

Use Cases

  • Searching a character in passwords, names, or data inputs.
  • Useful in character filtering logic.
  • Helps in understanding string traversal and condition checking.
Previous Article

Sort an Array in Ascending Order Using Insertion, Bubble, Selection, Merge, Quick, and Heap Sort in C

Next Article

Replace a Character in a Given String Using C Programming

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Subscribe to our Newsletter

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨