In C programming, character and string functions are indispensable tools for handling text data. This article will provide a detailed introduction to the definitions, functions, usage methods of these two types of functions, and help readers better understand and apply them through example code.
1. Character Functions
Character functions are typically located in the ctype.h
header file. They operate on individual characters, determining the character type or transforming the character.
1.1 Character Classification Functions
Function | Returns True if the Argument Meets the Condition |
---|---|
iscntrl | Control characters: page break , newline , carriage return , tab , vertical tab , etc. |
isspace | Whitespace characters: space ' ' , page break , newline , carriage return , tab , vertical tab , etc. |
isdigit | Decimal digits 0~9 |
isxdigit | Hexadecimal digits, including decimal digits, lowercase letters a~f , uppercase letters A~F |
islower | Lowercase letters a~z |
isupper | Uppercase letters A~Z |
isalpha | Letters a~z or A~Z |
isalnum | Letters or digits a~z, A~Z, 0~9 |
ispunct | Punctuation characters, any graphical character that is not a letter or digit (printable) |
isgraph | Any graphical character |
isprint | Any printable character, including graphical characters and whitespace characters |
Usage Example:
The usage of these functions is very similar. Here is an example for one function, the rest follow similarly:
int islower(int c); // Checks if the character is a lowercase letter // Returns a non-zero integer if it's a lowercase letter, otherwise returns 0.
Code Example: Convert lowercase letters in a string to uppercase:
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <ctype.h> int main() { int i = 0; char str[] = "i love China "; char c; while (str[i]) { c = str[i]; if (islower(c)) c -= 32; putchar(c); i++; } return 0; }
1.2 Character Conversion Functions
tolower(int ch);
// Converts uppercase letters to lowercase.toupper(int ch);
// Converts lowercase letters to uppercase.
Example:
In the code above, we used -32
to convert to uppercase. With these conversion functions, you can directly use toupper
:
#include <stdio.h> #include <ctype.h> int main() { int i = 0; char str[] = "i love China "; char c; while (str[i]) { c = str[i]; c = toupper(c); // Use function to convert putchar(c); i++; } return 0; }
2. String Functions
String functions are typically located in the <string.h>
header file. They operate on null-terminated strings.
2.1 gets
and puts
Both gets
and puts
are defined in <stdio.h>
, whereas the others are defined in <string.h>
.
gets
Function Prototype:
char *gets(char *str);
Parameters:
str
: A pointer to a character array where the string will be stored.
Functionality:
The
gets
function reads a line of input until it encounters a newline character, replacing the newline character with a null terminator�
.
puts
Function Prototype:
int puts(const char *str);
Parameters:
str
: A pointer to a null-terminated string.
Functionality:
The
puts
function outputs the string pointed to bystr
and appends a newline character at the end. It does not check or output embedded newline characters in the string.
Return Value:
Returns a non-negative value on success.
Returns EOF (typically
-1
) on failure.
Example:
#include <stdio.h> #include <string.h> int main() { char str[20]; printf("Input: "); gets(str); printf("Output: "); puts(str); return 0; }
2.2 strlen
Function Prototype:
size_t strlen(const char *s);
Parameters:
s
: A pointer to the string whose length is to be computed (must be null-terminated).
Functionality:
The
strlen
function counts the number of characters in the string, excluding the null terminator�
.
Return Value:
Returns the number of characters in the string (excluding
�
).
Example:
#include <stdio.h> #include <string.h> int main() { char* str = "Hello World"; printf("%d", strlen(str)); return 0; }
2.3 strcpy
Function Prototype:
char *strcpy(char *dest, const char *src);
Parameters:
dest
: A pointer to the destination string, which should have enough space to hold the source string and the null terminator.src
: A pointer to the source string, which must be null-terminated.
Functionality:
The
strcpy
function copies the source string to the destination string and adds a null terminator to the destination.
Return Value:
Returns the
dest
pointer.
Example:
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <string.h> int main() { char src[] = "Hello, World!"; char dest[20] = {0}; strcpy(dest, src); printf("Copied string: %s ", dest); return 0; }
2.4 strncpy
Function Prototype:
char *strncpy(char *dest, const char *src, size_t n);
Parameters:
dest
: A pointer to the destination string, which should have enough space to hold a part of the source string and the null terminator.src
: A pointer to the source string, which must be null-terminated.n
: The maximum number of characters to copy.
Functionality:
The
strncpy
function copies up ton
characters from the source string to the destination string. If the source string is shorter thann
, the remaining characters in the destination string are filled with null terminators.
Return Value:
Returns the
dest
pointer.
Example:
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <string.h> int main() { char src[] = "Hello, World!"; char dest[20] = {0}; strncpy(dest, src, 5); printf("Copied string: %s ", dest); return 0; }
2.5 strcat
Function Prototype:
char *strcat(char *dest, const char *src);
Parameters:
dest
: A pointer to the destination string, which should have enough space to hold the source string and the null terminator.src
: A pointer to the source string.
Functionality:
The
strcat
function appends the source string to the destination string and adds a null terminator at the end.
Return Value:
Returns the
dest
pointer.
Example:
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <string.h> int main() { char dest[20] = "Hello, "; char src[] = "World!"; strcat(dest, src); printf("Concatenated string: %s ", dest); return 0; }
2.6 strncat
The usage of strncat
is similar to the strcat
function, but it specifies the maximum number of characters to concatenate, thus avoiding the risk of buffer overflow.
Function prototype:
char *strncat(char *dest, const char *src, size_t n);
Parameters:
dest
: A pointer to the destination string, which must be large enough to hold the concatenated string, including the terminating null character�
.src
: A pointer to the source string, i.e., the string to append.n
: The maximum number of characters to copy fromsrc
todest
.
Functionality:
The strncat
function appends the first n
characters (excluding the null character �
) of the string pointed to by src
to the end of the string pointed to by dest
, and automatically adds a null character �
at the end of the result. If the number of characters in src
is less than n
, strncat
copies the entire src
string.
Return value:
The function returns a pointer to the destination string dest
.
Usage example:
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <string.h> int main() { char dest[20] = "Hello, "; const char src[] = "World!!!!"; // Use strncat to append the string strncat(dest, src, 5); // Append only "World" (5 characters) and the null character // Print result printf("The concatenated string is: '%s' ", dest); return 0; }
2.7 strcmp
Function prototype:
int strcmp(const char *s1, const char *s2);
Parameters:
s1
: A pointer to the first string to compare.s2
: A pointer to the second string to compare.
Functionality:
The strcmp
function compares two null-terminated strings s1
and s2
. The comparison is based on the ASCII values of the characters, comparing them one by one until a difference is found or the end of a string is reached (�
).
Return value:
If
s1
is equal tos2
, it returns 0.If
s1
is less thans2
, it returns a negative value.If
s1
is greater thans2
, it returns a positive value.
Usage example:
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <string.h> int main() { const char* str1 = "Hello"; const char* str2 = "World"; int result = strcmp(str1, str2); if (result < 0) { printf("'%s' is less than '%s' ", str1, str2); } else if (result > 0) { printf("'%s' is greater than '%s' ", str1, str2); } else { printf("'%s' is equal to '%s' ", str1, str2); } return 0; }
2.8 strncmpstrncmp
works similarly to the strcmp
function, but it specifies the maximum number of characters to compare, thus avoiding the risk of buffer overflow.
Function prototype:
int strncmp(const char *s1, const char *s2, size_t n);
Parameters:
s1
: A pointer to the first string to compare.s2
: A pointer to the second string to compare.n
: Specifies the number of characters to compare. The comparison is limited to the firstn
characters ofs1
ands2
.
Functionality:
Compares the first n
characters of s1
and s2
. If they are equal, the comparison continues with the next characters. If any difference is found, the comparison ends. The string with the larger character is considered greater. If all n
characters are equal, it returns 0.
Return value:
If the first
n
characters ofs1
ands2
are equal, it returns 0.If a character in
s1
is less than the corresponding character ins2
before comparingn
characters, it returns a negative value.If a character in
s1
is greater than the corresponding character ins2
before comparingn
characters, it returns a positive value.
Usage example:
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <string.h> int main() { const char* str1 = "Hello"; const char* str2 = "World"; int result = strncmp(str1, str2, 1); // Compare only the first character, i.e., H and W if (result < 0) { printf("'%s' is less than '%s' ", str1, str2); } else if (result > 0) { printf("'%s' is greater than '%s' ", str1, str2); } else { printf("'%s' is equal to '%s' ", str1, str2); } return 0; }
2.9 strstr
Function prototype:
char *strstr(const char *haystack, const char *needle);
Parameters:
haystack
: A pointer to the string to search.needle
: A pointer to the substring to find.
Functionality:
The strstr
function finds the first occurrence of the substring needle
in the string haystack
. The search is case-sensitive.
Return value:
If
needle
is a substring ofhaystack
,strstr
returns a pointer to the first occurrence ofneedle
inhaystack
.If
needle
is not a substring ofhaystack
,strstr
returns NULL.
Usage example:
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <string.h> int main() { const char* str = "Hello, world!"; const char* substr = "world"; char* pos = strstr(str, substr); if (pos) { printf("Found '%s' in '%s' at position: %ld ", substr, str, (long)(pos - str)); } else { printf("'%s' not found in '%s' ", substr, str); } return 0; }
2.10 strchr
Function prototype:
char *strchr(const char *s, int c);
Parameters:
s
: A pointer to the string to search.c
: The ASCII value of the character to find.
Functionality:
The strchr
function finds the first occurrence of the specified character c
in the string s
. The search does not include the terminating null character �
.
Return value:
If the specified character is found,
strchr
returns a pointer to that character.If the character is not found,
strchr
returns NULL.
Usage example:
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <string.h> int main() { const char* str = "Hello, world!"; char ch = 'o'; // strchr returns a pointer to the first 'o' character in the string char* pos = strchr(str, ch); if (pos) { printf("Found '%c' in '%s' at position: %ld ", ch, str, (long)(pos - str)); } else { printf("'%c' not found in '%s' ", ch, str); } return 0; }
2.11. strtok
Function Prototype:
char *strtok(char *str, const char *delim);
Parameters:
str
: A pointer to the string to be tokenized. On the first call, this pointer should point to the string to be tokenized. In subsequent calls, this pointer should be set toNULL
so the function continues processing from where it stopped previously.delim
: A pointer to a string containing delimiter characters.
Functionality:The strtok
function breaks the string str
into a series of tokens separated by the delimiters specified in the delim
parameter. On the first call, strtok
replaces the first delimiter in the string str
with a null character ('�'
) and returns a pointer to the token. In subsequent calls, the first parameter should be set to NULL
, so the function continues from the last token found.
Return Value:
On success,
strtok
returns a pointer to the next token.If no more tokens are found,
strtok
returnsNULL
.
Example Usage:
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <string.h> int main() { char str[] = "This is a sample string"; const char* delimiters = " ,."; char* token; // First call to provide the string to tokenize token = strtok(str, delimiters); while (token != NULL) { printf("%s ", token); // Print the current token token = strtok(NULL, delimiters); // Subsequent calls use NULL } return 0; }
2.12 strlwr
Function Prototype:
char *strlwr(char *str);
Parameters:
str
: A pointer to the string to be converted to lowercase.
Functionality:The strlwr
function converts all uppercase letters in the string str
to their corresponding lowercase letters, while other characters remain unchanged.
Return Value:The strlwr
function returns a pointer to the converted string, which is the same as the input string str
.
Example Usage:
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <string.h> int main() { char str[] = "HELLO WORLD!"; char* lower_str = strlwr(str); printf("%s ", lower_str); return 0; }
2.13 strupr
Function Prototype:
char *strupr(char *str);
Parameters:
str
: A pointer to the string to be converted to uppercase.
Functionality:The strupr
function converts all lowercase letters in the string str
to their corresponding uppercase letters, while other characters remain unchanged.
Return Value:The strupr
function returns a pointer to the converted string, which is the same as the input string str
.
Example Usage:
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <string.h> int main() { char str[] = "hello world!"; char* upper_str = strupr(str); printf("%s ", upper_str); return 0; }
2.14 strerror
Function Prototype:
char *strerror(int errnum);
Parameters:
errnum
: The error code, which is an integer typically obtained from system calls or library functions (e.g., from theerrno
variable).
Functionality:Returns a pointer to a string describing the error. This string corresponds to the error message for the error code specified by errnum
.
Return Value:
Returns a pointer to a string in a static buffer that describes the error. If
errnum
is not a valid error code, it returnsNULL
.
Different systems and implementations of the C standard library define error codes, which are usually documented in the errno.h
header file. At the start of a C program, the global variable errno
is initialized to 0, meaning no errors. When a standard library function encounters an error, the corresponding error code is stored in errno
. Since error codes are integers and may be difficult to interpret, each code is associated with a descriptive error message. The strerror
function provides the address of this descriptive error message as a string.
Example Usage:
#define _CRT_SECURE_NO_WARNINGS #include <errno.h> #include <string.h> #include <stdio.h> int main() { int i = 0; for (i = 0; i <= 10; i++) { printf("%s ", strerror(i)); } return 0; }
Output on Windows 11 + VS2022
Another Example:
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <string.h> #include <errno.h> int main() { FILE* pFile; // Attempt to open a non-existent file pFile = fopen("unexist.ent", "r"); if (pFile == NULL) // Print error message printf("Error opening file unexist.ent: %s ", strerror(errno)); return 0; }
2.15 perror
Function Prototype:
void perror(const char *s);
Parameters:
s
: A custom prefix string used to add context before the error message. This helps clarify the error's context.
Functionality:Prints a string containing an error message. The output consists of the prefix string s
followed by the error message corresponding to the current value of errno
. The message is sent to the standard error stream (stderr
).
Return Value:The perror
function does not return a value. It directly outputs the error message to stderr
.
Example Usage:
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <string.h> #include <errno.h> int main() { FILE* pFile; // Attempt to open a non-existent file pFile = fopen("unexist.ent", "r"); if (pFile == NULL) // Print error message perror("Error opening file unexist.ent:"); return 0; }
The perror
function essentially combines the tasks of handling and printing the error message, as done in the previous example with strerror
. It automatically appends a colon and a space to the user-provided prefix string, followed by the error message.
Summary:
When using
strerror
, you need to handle and print the error message manually.When using
perror
, the error message is automatically output tostderr
, and you only need to provide a meaningful prefix.