isdigit() function in C
0 228
The isdigit() function in C is used to determine if a character is a digit or not.
It checks whether a character falls within the range of '0' to '9'.
This function is part of the
Syntax:
int isdigit(int c);
Steps:
Include Header File: Include the
Call the Function: Pass a character or an integer representing a character as an argument to the isdigit() function.
Check Return Value: The function returns an integer:
If the character is a digit (0-9), it returns a non-zero value (typically 1).
If the character isn't a digit, the function returns 0.
Parameters:
c: It's an integer representing a character.
Return Value:
The isdigit() function returns an integer:
It returns a non-zero value (usually 1) if the character c is a digit.
It returns 0 if the character c is not a digit.
Examples:
Check if a Character is a Digit:
// Program to check if a character is a digit #include<stdio.h>#include<ctype.h> int main() { char ch = '7'; if (isdigit(ch)) { printf("%c is a digit\n", ch); } else { printf("%c is not a digit\n", ch); } return 0; }
Output:
7 is a digit
Check if Characters in a String are Digits:
// program to check if characters in a string are digits #include<stdio.h>#include<ctype.h> int main() { char str[] = "Hello123"; for (int i = 0; str[i] != '\0'; ++i) { if (isdigit(str[i])) { printf("%c is a digit\n", str[i]); } else { printf("%c is not a digit\n", str[i]); } } return 0; }
Output:
H is not a digit e is not a digit l is not a digit l is not a digit o is not a digit 1 is a digit 2 is a digit 3 is a digit
Count the Number of Digits in a String:
// program to count number of digits in a strings #include<stdio.h>#include<ctype,h> int main() { char str[] = "Hello123"; int count = 0; for (int i = 0; str[i] != '\0'; ++i) { if (isdigit(str[i])) { count++; } } printf("Number of digits in the string: %d\n", count); return 0; }
Output:
Number of digits in the string: 3
Extract Digits from a String:
program to extract digit from a string #include<stdio.h>#include<ctype.h> int main() { char str[] = "Hello123"; printf("Digits in the string: "); for (int i = 0; str[i] != '\0'; ++i) { if (isdigit(str[i])) { printf("%c ", str[i]); } } printf("\n"); return 0; }
Output:
Digits in the string: 1 2 3
Share:
Comments
Waiting for your comments