String Format Validation | C Programming Example

preview_player
Показать описание
Рекомендации по теме
Комментарии
Автор

Nice 🙃.

_Bool is_postal (char *input){

if (strlen(input) != 7) return false;
if (!isalpha(input[0])) return false;
if (!isdigit(input[1])) return false;
if (!isalpha(input[2])) return false;
if (input[3] != ' ') return false;
if (!isdigit(input[4])) return false;
if (!isalpha(input[5])) return false;
if (!isdigit(input[6])) return false;
return true;
}

justcurious
Автор

Man if that was your actual source code and the postal code was a user input then there would be all types of fun stuff going into your backend

ariyanshaikh
Автор

#include <stdio.h>
#include <string.h> // needed for strlen

int is_postal_code(char postal_code[]);

int main()
{
char code1[] = "L8K 4B6"; // valid
char code2[] = "L86 4B65"; // too long
char code3[] = "L864B6"; // missing space
char code4[] = "L8G 4BG"; // last char is not a digit

if (is_postal_code(code1)) printf("%s is a postal code\n", code1);
else printf("%s is not a postal code\n", code1);

if (is_postal_code(code2)) printf("%s is a postal code\n", code2);
else printf("%s is not a postal code\n", code2);

if (is_postal_code(code3)) printf("%s is a postal code\n", code3);
else printf("%s is not a postal code\n", code3);

if (is_postal_code(code4)) printf("%s is a postal code\n", code4);
else printf("%s is not a postal code\n", code4);

return 0;
}

// returns 1 if postal_code contains a postal_code and 0 otherwise
int is_postal_code(char postal_code[])
{
// check for all conditions that could break the postal code pattern
if (strlen(postal_code) != 7) return 0;
if (!(postal_code[0] >= 'A' && postal_code[0] <= 'Z')) return 0;
if (!(postal_code[1] >= '0' && postal_code[1] <= '9')) return 0;
if (!(postal_code[2] >= 'A' && postal_code[2] <= 'Z')) return 0;
if (postal_code[3] != ' ') return 0;
if (!(postal_code[4] >= '0' && postal_code[4] <= '9')) return 0;
if (!(postal_code[5] >= 'A' && postal_code[5] <= 'Z')) return 0;
if (!(postal_code[6] >= '0' && postal_code[6] <= '9')) return 0;

// if none of the above, we have a postal code!
return 1;
}

ridwanmugdha
Автор

hello! i have a question, what if i want to let the user input the value that’s going to be evaluated?

Jorhie
Автор

thank you so much for the video, it helped me in my project.

kookiekook