天天看點

Pointers on C——9 Strings, Characters, and Bytes.1

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