第 22 / 187 篇

2.6. 字符串与字符串库

说明

本文是个人学习用的非官方中英对照译文,原文:https://diveintosystems.org/book/C2-C_depth/strings.html。
原书采用 CC BY-NC-ND 4.0 许可(禁止演绎),请勿公开传播本译文。
标为「译注」「现代更新」的内容是译者补充,不代表原书作者观点;代码与原文逐字一致,未作改动。

2.6. Strings and the String Library

上一章我们介绍了 C 中的数组和字符串。本章讨论动态分配的 C 字符串,以及它们与 C 字符串库的配合使用。我们先简要回顾一下静态声明的字符串。

In the previous chapter we introduced arrays and strings in C. In this chapter we discuss dynamically allocated C strings and their use with the C string library. We first give a brief overview of statically declared strings.

2.6.1. C 对静态分配字符串(char 数组)的支持

2.6.1. C’s Support for Statically Allocated Strings (Arrays of char)

C 不支持单独的字符串类型,但在 C 程序中可以用一个以特殊空字符值 '\0' 结尾的 char 数组来实现字符串。结尾的空字符标示出构成字符串的字符序列在哪里结束。并非每个字符数组都是 C 字符串,但每个 C 字符串都是一个 char 数组。

C does not support a separate string type, but a string can be implemented in C programs using an array of char values that is terminated by a special null character value '\0'. The terminating null character identifies the end of the sequence of character values that make up a string. Not every character array is a C string, but every C string is an array of char values.

由于字符串在程序中经常出现,C 提供了含有字符串操作函数的库。使用 C 字符串库的程序需要包含 string.h。大多数字符串库函数都要求程序员为函数所操作的字符数组分配空间。打印字符串的值时,使用 %s 占位符。

Because strings frequently appear in programs, C provides libraries with functions for manipulating strings. Programs that use the C string library need to include string.h. Most string library functions require the programmer to allocate space for the array of characters that the functions manipulate. When printing out the value of a string, use the %s placeholder.

下面是一个使用字符串和一些字符串库函数的示例程序:

Here’s an example program that uses strings and some string library functions:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <stdio.h>
#include <string.h> // include the C string library

int main(void) {
char str1[10];
char str2[10];

str1[0] = 'h';
str1[1] = 'i';
str1[2] = '\0'; // explicitly add null terminating character to end

// strcpy copies the bytes from the source parameter (str1) to the
// destination parameter (str2) and null terminates the copy.
strcpy(str2, str1);
str2[1] = 'o';
printf("%s %s\n", str1, str2); // prints: hi ho

return 0;
}

2.6.2. 动态分配字符串

2.6.2. Dynamically Allocating Strings

字符数组可以动态分配(如指针和数组两节所述)。动态分配存放字符串的空间时,一定要记得在数组中为字符串末尾的结束符 '\0' 留出空间。

Arrays of characters can be dynamically allocated (as discussed in the Pointers and Arrays sections). When dynamically allocating space to store a string, it’s important to remember to allocate space in the array for the terminating '\0' character at the end of the string.

下面的示例程序演示了静态分配和动态分配的字符串(注意传给 malloc 的值):

The following example program demonstrates static and dynamically allocated strings (note the value passed to malloc):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
int size;
char str[64]; // statically allocated
char *new_str = NULL; // for dynamically allocated

strcpy(str, "Hello");
size = strlen(str); // returns 5

new_str = malloc(sizeof(char) * (size+1)); // need space for '\0'
if(new_str == NULL) {
printf("Error: malloc failed! exiting.\n");
exit(1);
}
strcpy(new_str, str);
printf("%s %s\n", str, new_str); // prints "Hello Hello"

strcat(str, " There"); // concatenate " There" to the end of str
printf("%s\n", str); // prints "Hello There"

free(new_str); // free malloc'ed space when done
new_str = NULL;

return 0;
}

原书警示 · C 字符串函数与目标内存(C String Functions and Destination Memory)

许多 C 字符串函数(尤其是 strcpy 和 strcat)沿着一个目标(destination)字符串指针(char *)参数,把结果写到它所指向的位置。这类函数假定目标处有足够的内存存放结果。因此,作为程序员,你必须在调用这些函数之前确保目标处有足够的可用内存。

没有分配足够的内存会产生未定义的结果,后果从程序崩溃到严重的安全漏洞不等。例如,下面对 strcpy 和 strcat 的调用展示了 C 新手常犯的错误:

1
2
3
4
5
6
7
8
9
10
11
// Attempt to write a 12-byte string into a 5-character array.
char mystr[5];
strcpy(mystr, "hello world");

// Attempt to write to a string with a NULL destination.
char *mystr = NULL;
strcpy(mystr, "try again");

// Attempt to modify a read-only string literal.
char *mystr = "string literal value";
strcat(mystr, "string literals aren't writable");

Many C string functions (notably strcpy and strcat) store their results by following a destination string pointer (char *) parameter and writing to the location it points to. Such functions assume that the destination contains enough memory to store the result. Thus, as a programmer, you must ensure that sufficient memory is available at the destination prior to calling these functions.

Failure to allocate enough memory will yield undefined results that range from program crashes to major security vulnerabilities. For example, the following calls to strcpy and strcat demonstrate mistakes that novice C programmers often make:

1
2
3
4
5
6
7
8
9
10
11
// Attempt to write a 12-byte string into a 5-character array.
char mystr[5];
strcpy(mystr, "hello world");

// Attempt to write to a string with a NULL destination.
char *mystr = NULL;
strcpy(mystr, "try again");

// Attempt to modify a read-only string literal.
char *mystr = "string literal value";
strcat(mystr, "string literals aren't writable");

2.6.3. 操作 C 字符串和字符的库

2.6.3. Libraries for Manipulating C Strings and Characters

C 提供了几个含有字符串和字符操作函数的库。在编写使用 C 字符串的程序时,字符串库(string.h)尤其有用。stdlib.h 和 stdio.h 库中也有字符串操作函数,而 ctype.h 库中有操作单个字符值的函数。

C provides several libraries with functions for manipulating strings and characters. The string library (string.h) is particularly useful when writing programs that use C strings. The stdlib.h and stdio.h libraries also contain functions for string manipulation, and the ctype.h library contains functions for manipulating individual character values.

使用 C 字符串库函数时要记住,大多数函数既不为它们所操作的字符串分配空间,也不检查你传入的字符串是否有效;你的程序必须为 C 字符串库要使用的字符串分配空间。此外,如果库函数会修改传入的字符串,调用者需要确保该字符串格式正确(即末尾有结束符 \0)。用错误的数组实参调用字符串库函数,常常会导致程序崩溃。各个库函数的文档(例如手册页)会说明该库函数是自己分配空间,还是由调用者负责把已分配好的空间传给它。

When using C string library functions, it’s important to remember that most do not allocate space for the strings they manipulate, nor do they check that you pass in valid strings; your program must allocate space for the strings that the C string library will use. Furthermore, if the library function modifies the passed string, the caller needs to ensure that the string is correctly formatted (that is, it has a terminating \0 character at the end). Calling string library functions with bad array argument values will often cause a program to crash. The documentation (for example, manual pages) for different library functions specifies whether the library function allocates space or if the caller is responsible for passing in allocated space to the library function.

现代更新(截至 2026-11)· 新进入标准的字符串函数

原书写作之后,C 和 POSIX 标准都补充了常用的字符串函数:C23 把原本只在 POSIX 中提供的 strdup(复制字符串,空间用 malloc 分配,用完需要 free)和 strndup 纳入了 C 标准库;POSIX.1-2024 则正式收录了 strlcpy 和 strlcat。cppreference:strdup · cppreference:strndup · man7:strlcpy(3)

原书注 · char[] 与 char * 形参以及 char * 返回类型(char[] and char * Parameters and char * Return Type)

静态声明的字符数组和动态分配的字符数组都可以传给 char * 形参,因为这两种变量的名字都求值为数组在内存中的基地址。把形参声明为 char [] 类型,对静态分配和动态分配的实参也都适用,但指定字符串(char 数组)形参的类型时,更常用的是 char *。

如果函数返回一个字符串(返回类型是 char *),它的返回值只能赋给同样是 char * 类型的变量,不能赋给静态分配的数组变量。之所以有这个限制,是因为静态声明的数组变量的名字不是合法的左值(它在内存中的基地址不能改变),所以不能被赋予 char * 返回值。

Both statically declared and dynamically allocated arrays of characters can be passed to a char * parameter because the name of either type of variable evaluates to the base address of the array in memory. Declaring the parameter as type char [] will also work for both statically and dynamically allocated argument values, but char * is more commonly used for specifying the type of string (array of char) parameters.

If a function returns a string (its return type is a char *), its return value can only be assigned to a variable whose type is also char *; it cannot be assigned to a statically allocated array variable. This restriction exists because the name of a statically declared array variable is not a valid lvalue (its base address in memory cannot be changed), so it cannot be assigned a char * return value.

strlen、strcpy、strncpy

strlen, strcpy, strncpy

字符串库提供了复制字符串和求字符串长度的函数:

The string library provides functions for copying strings and finding the length of a string:

译注 · 函数原型是简化过的

本节列出的原型为了易读做了简化。标准库中的实际声明是:size_t strlen(const char *s);、char *strcpy(char *restrict dst, const char *restrict src);、char *strncpy(char *restrict dst, const char *restrict src, size_t n);。也就是说 strlen 返回的是无符号的 size_t 而不是 int,不会被修改的源字符串参数带有 const。用 man strlen 等命令可以查看所在系统上的准确原型。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// returns the number of characters in the string (not including the null character)
int strlen(char *s);

// copies string src to string dst up until the first '\0' character in src
// (the caller needs to make sure src is initialized correctly and
// dst has enough space to store a copy of the src string)
// returns the address of the dst string
char *strcpy(char *dst, char *src);

// like strcpy but copies up to the first '\0' or size characters
// (this provides some safety to not copy beyond the bounds of the dst
// array if the src string is not well formed or is longer than the
// space available in the dst array); size_t is an unsigned integer type
char *strncpy(char *dst, char *src, size_t size);

在源字符串可能比目标字符串总容量更长的情况下,使用 strcpy 是不安全的。这时应当使用 strncpy。size 参数使 strncpy 从 src 字符串向 dst 字符串复制的字符不超过 size 个。当 src 字符串的长度大于或等于 size 时,strncpy 把 src 的前 size 个字符复制到 dst,不会在 dst 末尾添加空字符。因此,程序员应当在调用 strncpy 之后显式地在 dst 末尾加上空字符。

The strcpy function is unsafe to use in situations when the source string might be longer than the total capacity of the destination string. In this case, one should use strncpy. The size parameter stops strncpy from copying more than size characters from the src string into the dst string. When the length of the src string is greater than or equal to size, strncpy copies the first size characters from src to dst and does not add a null character to the end of the dst. As a result, the programmer should explicitly add a null character to the end of dst after calling strncpy.

下面是在程序中使用这些函数的一些例子:

Here are some example uses of these functions in a program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <stdio.h>
#include <stdlib.h>
#include <string.h> // include the string library

int main(void) {
// variable declarations that will be used in examples
int len, i, ret;
char str[32];
char *d_str, *ptr;

strcpy(str, "Hello There");
len = strlen(str); // len is 11

d_str = malloc(sizeof(char) * (len+1));
if (d_str == NULL) {
printf("Error: malloc failed\n");
exit(1);
}

strncpy(d_str, str, 5);
d_str[5] = '\0'; // explicitly add null terminating character to end

printf("%d:%s\n", strlen(str), str); // prints 11:Hello There
printf("%d:%s\n", strlen(d_str), d_str); // prints 5:Hello

free(d_str);

return 0;
}

原书注 · strlcpy(strlcpy)

strlcpy 函数与 strncpy 类似,只是它总会在目标字符串末尾加上 '\0' 字符。由于总是会终止字符串,它比 strncpy 更安全,因为不需要程序员记着显式地给字符串加上终止符。

1
2
3
// like strncpy but copies up to the first '\0' or size-1 characters
// and null terminates the dest string (if size > 0).
char *strlcpy(char *dest, char *src, size_t size);

Linux 的 GNU C 库在较新的版本(2.38)中加入了 strlcpy。它目前只在部分系统上可用,但随着新版 C 库的普及,可用范围会越来越广。我们建议在 strlcpy 可用时使用它。

在提供 strlcpy 的系统上,上例中对 strncpy 的如下调用:

1
2
3
// copy up to 5 chars from str to d_str
strncpy(d_str, str, 5);
d_str[5] = '\0'; // explicitly add null terminating character to end

可以替换为对 strlcpy 的这个调用:

1
2
// copy up to 5 chars from str to d_str
strlcpy(d_str, str, 6); // strlcpy always adds '\0' to the end

The strlcpy function is similar to strncpy, except it always adds the '\0' character to the end of the destination string. Always terminating the string makes it a safer alternative to strncpy because it doesn’t require the programmer to remember to explicitly null terminate the string.

1
2
3
// like strncpy but copies up to the first '\0' or size-1 characters
// and null terminates the dest string (if size > 0).
char *strlcpy(char *dest, char *src, size_t size);

Linux’s GNU C library added strlcpy in a recent version (2.38). It’s currently only available on some systems, but its availability will increase as newer versions of the C library become more widespread. We recommend using strlcpy when it is available.

On systems where strlcpy is available, the following call to strncpy from the example above:

1
2
3
// copy up to 5 chars from str to d_str
strncpy(d_str, str, 5);
d_str[5] = '\0'; // explicitly add null terminating character to end

could be replaced with this call to strlcpy:

1
2
// copy up to 5 chars from str to d_str
strlcpy(d_str, str, 6); // strlcpy always adds '\0' to the end

译注 · strlcpy 的返回值

原文给出的原型 char *strlcpy(...) 有误:strlcpy 实际返回 size_t,即它试图创建的字符串的总长度(也就是 src 的长度)。如果返回值 ≥ size,说明发生了截断。macOS 和 BSD 很早就提供了 strlcpy;glibc 从 2.38 版开始提供,它也已被纳入 POSIX.1-2024 标准。man7:strlcpy(3)

strcmp、strncmp

strcmp, strncmp

字符串库还提供了比较两个字符串的函数。用 == 运算符比较字符串变量,并不会比较字符串中的字符——它只比较两个字符串的基地址。例如,表达式:

The string library also provides a function to compare two strings. Comparing string variables using the == operator does not compare the characters in the strings — it compares only the base addresses of the two strings. For example, the expression:

1
if (d_str == str) { ...

比较的是 d_str 所指向的堆中 char 数组的基地址,与栈上分配的 str char 数组的基地址。

compares the base address of the char array in the heap pointed to by d_str to the base address of the str char array allocated on the stack.

要比较字符串的值,程序员要么自己手写代码逐个比较对应的元素值,要么使用字符串库中的 strcmp 或 strncmp 函数:

To compare the values of the strings, a programmer needs to either write code by hand to compare corresponding element values, or use the strcmp or strncmp functions from the string library:

1
2
3
4
5
6
7
int strcmp(char *s1, char *s2);
// returns 0 if s1 and s2 are the same strings
// a value < 0 if s1 is less than s2
// a value > 0 if s1 is greater than s2

int strncmp(char *s1, char *s2, size_t n);
// compare s1 and s2 up to at most n characters

strcmp 函数根据字符的 ASCII 表示逐个字符地比较字符串。换句话说,它通过比较两个参数数组中对应位置的 char 值来得出字符串比较的结果,这有时会产生违反直觉的结果。例如,char 值 'a' 的 ASCII 编码比 char 值 'Z' 的编码大。因此,strcmp("aaa", "Zoo") 返回一个正值,表示 "aaa" 大于 "Zoo";而 strcmp("aaa", "zoo") 返回一个负值,表示 "aaa" 小于 "zoo"。

The strcmp function compares strings character by character based on their ASCII representation. In other words, it compares the char values in corresponding positions of the two parameter arrays to produce the result of the string comparison, which occasionally yields unintuitive results. For example, the ASCII encoding for the char value 'a' is larger than the encoding for the char value 'Z'. As a result, strcmp("aaa", "Zoo") returns a positive value indicating that "aaa" is greater than "Zoo", and a call to strcmp("aaa", "zoo") returns a negative value indicating that "aaa" is less than "zoo".

下面是一些字符串比较的例子:

Here are some string comparison examples:

1
2
3
4
5
6
7
8
9
10
11
12
13
strcpy(str, "alligator");
strcpy(d_str, "Zebra");

ret = strcmp(str,d_str);
if (ret == 0) {
printf("%s is equal to %s\n", str, d_str);
} else if (ret < 0) {
printf("%s is less than %s\n", str, d_str);
} else {
printf("%s is greater than %s\n", str, d_str); // true for these strings
}

ret = strncmp(str, "all", 3); // returns 0: they are equal up to first 3 chars

strcat、strstr、strchr

strcat, strstr, strchr

字符串库函数可以拼接字符串(注意,要由调用者确保目标字符串有足够的空间存放结果):

String library functions can concatenate strings (note that it’s up to the caller to ensure that the destination string has enough space to store the result):

1
2
3
4
5
6
7
// append chars from src to end of dst
// returns ptr to dst and adds '\0' to end
char *strcat(char *dst, char *src)

// append the first chars from src to end of dst, up to a maximum of size
// returns ptr to dst and adds '\0' to end
char *strncat(char *dst, char *src, size_t size);

它还提供了在字符串中查找子串或字符值的函数:

It also provides functions for finding substrings or character values in strings:

1
2
3
4
5
6
7
8
9
10
11
// locate a substring inside a string
// (const means that the function doesn't modify string)
// returns a pointer to the beginning of substr in string
// returns NULL if substr not in string
char *strstr(const char *string, const char *substr);

// locate a character (c) in the passed string (s)
// (const means that the function doesn't modify s)
// returns a pointer to the first occurrence of the char c in string
// or NULL if c is not in the string
char *strchr(const char *s, int c);

下面是使用这些函数的一些例子(为了便于阅读,省略了部分错误处理):

Here are some examples using these functions (we omit some error handling for the sake of readability):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
char str[32];
char *ptr;

strcpy(str, "Zebra fish");
strcat(str, " stripes"); // str gets "Zebra fish stripes"
printf("%s\n", str); // prints: Zebra fish stripes

strncat(str, " are black.", 8);
printf("%s\n", str); // prints: Zebra fish stripes are bla (spaces count)

ptr = strstr(str, "trip");
if (ptr != NULL) {
printf("%s\n", ptr); // prints: tripes are bla
}

ptr = strchr(str, 'e');
if (ptr != NULL) {
printf("%s\n", ptr); // prints: ebra fish stripes are bla
}

strchr 和 strstr 的调用分别返回参数数组中第一个匹配的字符值或第一个匹配的子串值所在元素的地址。这个元素地址是一个以 \0 字符结尾的 char 值数组的起点。换句话说,ptr 指向另一个字符串内部某个子串的开头。用 printf 把 ptr 的值当作字符串打印时,会打印从 ptr 所指下标开始的字符值,于是得到上面列出的结果。

Calls to strchr and strstr return the address of the first element in the parameter array with a matching character value or a matching substring value, respectively. This element address is the start of an array of char values terminated by a \0 character. In other words, ptr points to the beginning of a substring inside another string. When printing the value of ptr as a string with printf, the character values starting at the index pointed to by ptr are printed, yielding the results listed above.

strtok、strtok_r

strtok, strtok_r

字符串库还提供了把字符串切分成记号的函数。记号(token)指的是字符串中被任意数量的、由程序员选定的分隔符隔开的一段字符子序列。

The string library also provides functions that divide a string into tokens. A token refers to a subsequence of characters in a string separated by any number of delimiter characters of the programmer’s choosing.

1
2
3
4
char *strtok(char *str, const char *delim);

// a reentrant version of strtok (reentrant is defined in later chapters):
char *strtok_r(char *str, const char *delim, char **saveptr);

strtok(或 strtok_r)函数在一个较长的字符串中找出各个记号。例如,把 strtok 的分隔符设为空白字符集合,就能从一个原本是英文句子的字符串中得到一个个单词。也就是说,句子中的每个单词都是字符串中的一个记号。

The strtok (or strtok_r) functions find individual tokens within a larger string. For example, setting strtok‘s delimiters to the set of whitespace characters yields words in a string that originally contains an English sentence. That is, each word in the sentence is a token in the string.

下面是一个用 strtok 把输入字符串中的各个单词作为记号找出来的示例程序(也可以从这里复制:strtokexample.c)。

Below is an example program that uses strtok to find individual words as the tokens in an input string. (it can also be copied from here: strtokexample.c).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/*
* Extract whitespace-delimited tokens from a line of input
* and print them one per line.
*
* to compile:
* gcc -g -Wall strtokexample.c
*
* example run:
* Enter a line of text: aaaaa bbbbbbbbb cccccc
*
* The input line is:
* aaaaa bbbbbbbbb cccccc
* Next token is aaaaa
* Next token is bbbbbbbbb
* Next token is cccccc
*/

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main(void) {
/* whitespace stores the delim string passed to strtok. The delim
* string is initialized to the set of characters that delimit tokens
* We initialize the delim string to the following set of chars:
* ' ': space '\t': tab '\f': form feed '\r': carriage return
* '\v': vertical tab '\n': new line
* (run "man ascii" to list all ASCII characters)
*
* This line shows one way to statically initialize a string variable
* (using this method the string contents are constant, meaning that they
* cannot be modified, which is fine for the way we are using the
* whitespace string in this program).
*/
char *whitespace = " \t\f\r\v\n"; /* Note the space char at beginning */

char *token; /* The next token in the line. */
char *line; /* The line of text read in that we will tokenize. */

/* Allocate some space for the user's string on the heap. */
line = malloc(200 * sizeof(char));
if (line == NULL) {
printf("Error: malloc failed\n");
exit(1);
}

/* Read in a line entered by the user from "standard in". */
printf("Enter a line of text:\n");
line = fgets(line, 200 * sizeof(char), stdin);
if (line == NULL) {
printf("Error: reading input failed, exiting...\n");
exit(1);
}
printf("The input line is:\n%s\n", line);

/* Divide the string into tokens. */
token = strtok(line, whitespace); /* get the first token */
while (token != NULL) {
printf("Next token is %s\n", token);
token = strtok(NULL, whitespace); /* get the next token */
}

free(line);

return 0;
}

sprintf

sprintf

C 的 stdio 库也提供了操作 C 字符串的函数。其中最有用的大概是 sprintf 函数,它把输出「打印」到一个字符串中,而不是打印到终端:

The C stdio library also provides functions that manipulate C strings. Perhaps the most useful is the sprintf function, which “prints” into a string rather than printing output to a terminal:

译注

sprintf 和 strcpy 一样不检查目标空间大小,现代代码更推荐使用带长度参数的 snprintf(str, sizeof(str), ...),它最多写入指定字节数并总是以 '\0' 结尾。

1
2
3
// like printf(), the format string allows for placeholders like %d, %f, etc.
// pass parameters after the format string to fill them in
int sprintf(char *s, const char *format, ...);

sprintf 用各种类型的值来初始化一个字符串的内容。它的 format 参数与 printf 和 scanf 的类似。下面是一些例子:

sprintf initializes the contents of a string from values of various types. Its parameter format resembles those of printf and scanf. Here are some examples:

1
2
3
4
5
6
7
8
9
10
11
char str[64];
float ave = 76.8;
int num = 2;

// initialize str to format string, filling in each placeholder with
// a char representation of its arguments' values
sprintf(str, "%s is %d years old and in grade %d", "Henry", 12, 7);
printf("%s\n", str); // prints: Henry is 12 years old and in grade 7

sprintf(str, "The average grade on exam %d is %g", num, ave);
printf("%s\n", str); // prints: The average grade on exam 2 is 76.8

处理单个字符值的函数

Functions for Individual Character Values

标准 C 库(stdlib.h)中有一组用于处理和检测单个 char 值的函数,包括:

The standard C library (stdlib.h) contains a set of functions for manipulating and testing individual char values, including:

译注

准确地说,这组函数声明在 <ctype.h> 中(下面代码里也确实包含了它),而不是 stdlib.h。另外它们的参数和返回值类型都是 int:tolower/toupper 返回的是 int 而不是 char,传入的参数应当是 unsigned char 范围内的值或 EOF。

1
2
3
4
5
6
7
8
9
10
11
12
#include <stdlib.h>   // include stdlib and ctypes to use these
#include <ctype.h>

int islower(ch);
int isupper(ch); // these functions return a non-zero value if the
int isalpha(ch); // test is TRUE, otherwise they return 0 (FALSE)
int isdigit(ch);
int isalnum(ch);
int ispunct(ch);
int isspace(ch);
char tolower(ch); // returns ASCII value of lower-case of argument
char toupper(ch);

下面是它们的一些用法示例:

Here are some examples of their use:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
char str[64];
int len, i;

strcpy(str, "I see 20 ZEBRAS, GOATS, and COWS");

if ( islower(str[2]) ){
printf("%c is lower case\n", str[2]); // prints: s is lower case
}

len = strlen(str);
for (i = 0; i < len; i++) {
if ( isupper(str[i]) ) {
str[i] = tolower(str[i]);
} else if( isdigit(str[i]) ) {
str[i] = 'X';
}
}
printf("%s\n", str); // prints: i see XX zebras, goats, and cows

把字符串转换为其他类型的函数

Functions to Convert Strings to Other Types

stdlib.h 中还有在字符串和其他 C 类型之间转换的函数。例如:

stdlib.h also contains functions to convert between strings and other C types. For example:

1
2
3
4
#include <stdlib.h>

int atoi(const char *nptr); // convert a string to an integer
double atof(const char *nptr); // convert a string to a float

下面是一个例子:

Here’s an example:

译注

atoi 和 atof 无法报告错误:atoi("abc") 返回 0,与 atoi("0") 的结果无法区分。需要检查输入是否合法时,应使用 strtol、strtod 等函数,它们会通过结束指针参数和 errno 告诉你转换在哪里停下、是否溢出。

1
printf("%d %g\n", atoi("1234"), atof("4.56"));

想进一步了解这些以及其他 C 库函数(包括它们的作用、参数格式、返回值,以及使用时需要包含哪些头文件),请查看它们的手册页。例如,要查看 strcpy 的手册页,运行:

For more information about these and other C library functions (including what they do, their parameter format, what they return, and which headers need to be included to use them), see their man pages. For example, to view the strcpy man page, run:

1
$ man strcpy