06 CharactersandStrings
06 CharactersandStrings
Clearly, the length of array is the length of string plus 1, to account for the terminating null character '\0'.
You can use scanf() to input a string, and printf() to print a string, with %s conversion specifier. For
example,
1#include <stdio.h>
2#include <string.h>
3
4int main() {
5 char message[256];
6 // The length of char array shall be sufficient to hold the string
7 // plus the terminating null character '\0'
8 printf("Enter a message: ");
9 scanf("%s", message);
10 // Do not place an & before the array variable
11 printf("The message is: %s\n", message);
12 // Print up to but not including the terminating null character '\0'
13
14 // print each characters
15 int i;
16 for (i = 0; message[i] != '\0'; ++i) {
17 printf("'%c' ", message[i]);
18 }
19 printf("\n");
20
21 int len = strlen(message);
22 // Length of string does not include terminating null character '\0'
23 printf("The length of string is %d\n", len);
24 }
Take note that you need to allocate a char array that is big enough to hold the input string including the
terminating null character '\0'.
6.1 Character Type and Conversion in <
ctype.h> Header
Function Description
int isalpha(int c); [a-zA-Z] Check the character's type and return true
int isdigit(int c); [0-9] (non-zero) or false (0)
int isalnum(int c); [a-zA-Z0-9]
int isxdigit(int c); [0-9A-Fa-f]
int isspace(int c); [ \t\n]
int iscntrl(int c); Control character
int ispunct(int c); Punctuation character
int isprint(int c); Printable character
int isgraph(int c); Graphical character
supper(int c);
int i [A-Z] Check if uppercase/lowercase and return true
int i slower(int c); [a-z] (non-zero) or false (0)
oupper(int c);
int t To Uppercase Return the uppercase/lowercase character, if c is a
int t olower(int c); To Lowercase lowercase/uppercase character; otherwise, return c.
Function Description
int atoi(const char * str); String to int Convert the str to
double atof(const char * str); String to double int/double/long/long long.
long atol(const char * str); String to long
long long atoll(const char * str); String to long long
double strtod(const char* str, String to double Convert the str to
char** endptr); String to float double/float.
float strtof(const char* str, If endptr is not a null pointer,
char** endptr); it will be set to point to the first
character after the number.
long strtol(const char* str, String to long Convert the str to
char** endptr, int base); String to unsigned long/unsigned long.
unsigned long strtoul(const char* long
str, char** endptr, int base);