1.字符串函数总表
函数 | 头文件 | 功能 | 用法示例 | 关键点 |
---|
strdup | <string.h> | 把字符串复制到新分配的内存 | char *p = strdup("abc"); | 返回的新字符串需要 free |
strlen | <string.h> | 计算字符串长度(不含 \0 ) | int len = strlen("abc"); | 只计算到第一个 \0 |
strcpy | <string.h> | 把字符串拷贝到目标缓冲区 | strcpy(dst, src); | 目标必须有足够空间 |
strcat | <string.h> | 把字符串拼接到目标后面 | strcat(dst, src); | 目标缓冲区要够大 |
strchr | <string.h> | 在字符串中查找字符 | if (strchr(s, 'a')) | 返回指向第一个匹配字符的指针;找不到返回 NULL |
strcmp | <string.h> | 比较两个字符串 | if (strcmp(s1, s2) == 0) | 返回 0 表示相等 |
2.助记符
缩写 | 英文含义 | 中文解释 | 常见在哪 |
---|
str | string | 字符串 | 所有相关函数前缀 |
cpy | copy | 拷贝 | strcpy 、strncpy |
cat | concatenate | 拼接(连接) | strcat 、strncat |
cmp | compare | 比较 | strcmp 、strncmp |
chr | character | 字符 | strchr (找字符)、strrchr (反向找) |
dup | duplicate | 复制一份(新内存) | strdup |
3.文件操作小程序
📌 ✅ 题目:实现一个简单的内存中文本追加工具
此工具要支持:
以“追加模式”将内容写入到 File 对象的 content 中;
若写入失败,则追加固定的 “error” 字符串;
程序最后输出整个文件内容
#include <stdio.h>
#include <stdlib.h>
#include <string.h>typedef struct {char *name;char mode[4];char *content;
} File;File *file = NULL;void append_write(char* content)
{if (strchr(file->mode, 'a') == NULL) {return;}if (file->content == NULL) {file->content = strdup(content);return;}int new_len = strlen(file->content) + strlen(content);char *new_str = malloc(new_len + 1);strcpy(new_str, file->content);strcat(new_str, content);free(file->content);file->content = new_str;
}void append_err()
{char *err = "error";if (file->content == NULL) {file->content = strdup(err);return;}int new_len = strlen(file->content) + strlen(err);char *new_str = malloc(new_len + 1);strcpy(new_str, file->content);strcat(new_str, err);free(file->content);file->content = new_str;
}int main()
{file = malloc(sizeof(File));file->content = NULL;strcpy(file->mode, "a+");append_write("Hello ");append_write("world!");append_err();printf("File content: %s\n", file->content);free(file->content);free(file);return 0;
}