字符串常用函数(string.h)
1. 概念表
| 函数 | 作用 | 风险提示 |
|---|---|---|
| strlen | 长度(不含 \0) | 需保证 \0 存在 |
| strcpy | 拷贝 | 目标必须够大 |
| strcmp | 比较 | 返回 <0/0/>0 |
| strcat | 连接 | 极易溢出,慎用 |
2. 完整例子
| 1 | #include <stdio.h> |
| 2 | #include <string.h> |
| 3 | |
| 4 | int main(void) { |
| 5 | char buf[16] = "abc"; |
| 6 | printf("len=%zu\n", strlen(buf)); |
| 7 | if (strcmp(buf, "abc") == 0) { |
| 8 | printf("equal\n"); |
| 9 | } |
| 10 | strcpy(buf, "xyz"); |
| 11 | printf("%s\n", buf); |
| 12 | return 0; |
| 13 | } |