Strings are an important type of data, yet C does not have an explicit string data type because strings are stored in character arrays or as string literals. Literals are appropriate for strings that the program does not need to modify. All other strings must be stored in character arrays or dynamically allocated memory (see Chapter 11).This chapter describes the library functions that deal with strings and characters and a related group of functions with similar capabilities that deal with both string and nonstring data.
字符串是一种重要的数据类型,但是C 语言并没有显式的字符串数据类型,因为字符串以字符串常量的形式出现或者存储于字符数组中。字符串常量很适用于那些程序不会对它们进行修改的字符串。所有其他字符串都必须存储于宇符数组或动态分配的内存中(见第11 章)。本章描述处理字符串和字符的库函数,以及一组相关的,具有类似能力的,既可以处理字符串也可以处理非字符串数据的函数。
9.1 String Basics
First, letʹs review the basics of strings. A string is a sequence of zero or more characters followed by a NUL byte, which is a byte whose bits are all zero. Therefore, it is not possible for a string to contain a NUL as one of its characters. This restriction rarely causes problems because there isnʹt a printable character associated with NUL, which is why it was chosen as a terminator. The NUL terminates the string but is not considered a part of it, so the length of a string does not include the NUL.
首先,让我们回顾一下字符串的基础知识。字符串就是一串零个或多个字符,并且以一个位模式为全0 的NUL 字节结尾。因此,字符串所包含的字符内部不能出现NUL 字节。这个限制很少会引起问题,因为NUL 字节并不存在与它相关联的可打印字符,这也是它被选为终止符的原因。NUL字节是字符串的终止符,但它本身并不是字符串的一部分,所以字符串的长度并不包括NUL 字节。
The header file string.h contains the prototypes and declarations needed to use the string functions. Although its use is not required, it is a good idea to include this header file because with the prototypes it contains the compiler can do a better job error checking your program.
头文件string.h 包含了使用字符串函数所需的原型和声明。尽管并非必需,但在程序中包含这个头文件确实是个好主意,因为有了它所包含的原型,编译器可以更好地为你的程序执行错误检查。
上一章 Pointers on C——8 Arrays.22