C語言中的字符串習慣上是以null字符('/0')結尾的字符數組。編譯器在所有字符串常量後面自動添加一個多餘的null字符,但編程人員要保證字符數組中生成的字符串以null字符結尾。
以下是幾個基本的字符串處理函數:
strcat
#include <string.h>
char *strcat(char *dest, const char *src);
把src所指字符串添加到dest結尾處(覆蓋dest結尾處的'/0')並添加'/0'。
src和dest所指內存區域不可以重疊且dest必須有足夠的空間來容納src的字符串。
返回指向dest的指針。
strncat
#include <string.h>
char *strncat(char *dest, const char *src, size_t n);
把src所指字符串的前n個字符添加到dest結尾處(覆蓋dest結尾處的'/0')並添加'/0'。
src和dest所指內存區域不可以重疊且dest必須有足夠的空間來容納src的字符串。
返回指向dest的指針。
strcpy
#include <string.h>
char *strcpy(char *dest, const char *src);
將字符串src的內容複製到字符串dest,覆蓋dest中原先的內容。
複製整個src的內容並添加終止NULL字符,即使src比dest長。
函數strcpy返回dest。
strncpy
#include <string.h>
char *strncpy(char *dest, const char *src, size_t n);
strncpy不復制最後的'/0'結束符,所以是不安全的。
strlen
#include <string.h>
int strlen(char *s);
返回s的長度,不包括結束符NULL。
這幾個函數中,需要留意strncpy函數,此函數調用後不會自動在字符串尾添加'/0',需要手動添加。