C Programming - A really useful built in C library

in hive-175254 •  2 years ago 

Hi people ,

Today i am here with some high end coding example. We will learn about a library built in C program language that we can use to search a character from a string.

image.png

Source

Here is the program itself :

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

int main()
{
char str[100]; // Declare a string with maximum length 100
char ch; // Declare a character to search for

printf("Enter a string: ");
gets(str); // Read the string from the user

printf("Enter the character to search for: ");
scanf("%c", &ch); // Read the character from the user

// Use strchr function to search for the character in the string
char *result = strchr(str, ch);

if (result) // If the character was found
{
printf("Character '%c' found at index %ld\n", ch, result - str);
}
else // If the character was not found
{
printf("Character '%c' not found in the string\n", ch);
}

return 0;
}

The strchr function is a built-in C library function that searches for the first occurrence of a character in a string. It returns a pointer to the first occurrence of the character, or NULL if the character is not found.

In the above program, we use scanf to read a character from the user and store it in the ch variable. Then we use the strchr function to search for the character in the string. If the character is found, the program prints its index in the string. If the character is not found, the program prints a message indicating that it was not found.

Let us understand how this program works with the help of examples :

Screenshot 2022-12-16 231601.png

In this example, the user entered the string "Hello, world!" and the character 'o'. The program searches for the character 'o' in the string, and finds it at index 4 (the fifth character in the string). The program then prints a message indicating that the character was found at that index.

Screenshot 2022-12-16 231612.png

In this example, the user entered the same string as before, but searched for the character 'x', which is not present in the string. The program therefore prints a message indicating that the character was not found.

If you also want to learn coding then find your teacher according to your language. For me i am comfortable with hindi language and follow hindi teachers.

You can refer to my teacher below in case you are also comfortable with hindi.

Source

I will soon call myself a trader and a small programmer together.

Happy trading and keep learning what you love.

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!