C 標準庫的 string.h 提供了一整套以 NUL 結尾字串為前提的操作函數。以下依「複製、串接、比較、搜尋、轉換、分割」分類整理,並標明原型與行為重點。
char *strcpy(char *destin, char *source);char *strncpy(char *destin, char *source, int maxlen);char *strcat(char *destin, char *source);char *strdup(char *str);#include <stdio.h>
#include <string.h>
int main(void)
{
char destination[25];
char *blank = " ", *c = "C++", *Borland = "Borland";
strcpy(destination, Borland);
strcat(destination, blank);
strcat(destination, c);
printf("%s\n", destination); // Borland C++
return 0;
}
int strcmp(char *str1, char *str2);int strncmp(char *str1, char *str2, int maxlen);int stricmp(char *str1, char *str2);int strnicmp(char *str1, char *str2, unsigned maxlen);提醒:stricmp、strcmpi、strnicmp 並非 C 標準函數,而是各家編譯器(如 Borland、MSVC 的 _stricmp)的擴充,跨平台時需自行準備替代實作。
int ptr;
char *buf1 = "aaa", *buf2 = "bbb", *buf3 = "ccc";
ptr = strcmp(buf2, buf1);
printf("%d\n", ptr); // 正數
ptr = strcmp(buf2, buf3);
printf("%d\n", ptr); // 負數
char *strchr(char *str, char c);char *strstr(char *str1, char *str2);char *strpbrk(char *str1, char *str2);int strcspn(char *str1, char *str2);int strspn(char *str1, char *str2);char string[15];
char *ptr, c = 'r';
strcpy(string, "This is a string");
ptr = strchr(string, c);
if (ptr)
printf("The character %c is at position: %d\n", c, ptr - string);
else
printf("The character was not found\n");
用 ptr - string 這種指標相減的技巧取得位移量,是 C 字串處理常見手法。
char *strtok(char *str1, char *str2);char *strtok(char **str1, const char *delim);char input[16] = "abc,d";
char *p;
p = strtok(input, ",");
if (p) printf("%s\n", p); // abc
p = strtok(NULL, ",");
if (p) printf("%s\n", p); // d
char *strset(char *str, char c);char *strnset(char *str, char ch, unsigned n);char *strrev(char *str);void swab(char *from, char *to, int nbytes);char string[] = "abcdefghijklmnopqrstuvwxyz";
strnset(string, 'x', 13);
printf("%s\n", string); // xxxxxxxxxxxxxnopqrstuvwxyz
double strtod(char *str, char **endptr);long strtol(char *str, char **endptr, int base);char *string = "87654321", *endptr;
long lnumber = strtol(string, &endptr, 10);
printf("string = %s long = %ld\n", string, lnumber);
char *strerror(int errnum);extern int isalpha(int c);(需 include ctype.h)最後提醒一個實務重點:strcpy、strcat、sprintf 這類函數都不做邊界檢查,一旦目標緩衝區不足就會造成緩衝區溢位。在正式專案中,優先用 snprintf、strncpy 搭配明確的長度常數,或改用 strlcpy/strlcat 等更安全實作。