How to check a if a string contains a letter in c?

466 views Asked by At

I have to check if a character(string) contains a scanned letter.

char password[15]="STACKOVERFLOW";
char check;
printf("Type in a letter to check if it is in the password/n");
scanf("%c", check);

Now I want to check if the check is in the password and print true or false.

1

There are 1 answers

0
Vlad from Moscow On

For starters use

scanf(" %c", check);
       ^^^^

instead of

scanf("%c", check);

to skip white space characters from the input stream.

To check whether a character is present in a string use the standard function strchr declared in the header <string.h>. For example

#include <string.h>

//...


if ( strchr( password, check ) == NULL ) // if ( !strchr( password, check ) )
{
    puts( "The character is absent" );
}

Or

if ( strchr( password, check ) ) 
{
    puts( "Bingo! The character is present" );
}