当前位置: 首页 > news >正文

C语言中常见字符串处理函数

1.字符串函数总表

函数头文件功能用法示例关键点
strdup<string.h>把字符串复制到新分配的内存char *p = strdup("abc");返回的新字符串需要 free
strlen<string.h>计算字符串长度(不含 \0int 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.助记符

缩写英文含义中文解释常见在哪
strstring字符串所有相关函数前缀
cpycopy拷贝strcpystrncpy
catconcatenate拼接(连接)strcatstrncat
cmpcompare比较strcmpstrncmp
chrcharacter字符strchr(找字符)、strrchr(反向找)
dupduplicate复制一份(新内存)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;
}

相关文章:

  • Mybatis多条件查询设置参数的三种方法
  • Vue 3 Teleport 特性
  • [Python] -基础篇3-掌握Python中的条件语句与循环
  • UE5 Grid3D 学习笔记
  • 低延时高速数据链技术在无人平台(无人机无人船无人车)中的关键作用与应用
  • Android大图加载优化:BitmapRegionDecoder深度解析与实战
  • 认知智能平台搭载LLM+RAG,重构行业洞察与决策支持体系!
  • 零基础学习RabbitMQ(5)--工作模式(1)
  • Elasticsearch 索引设计与性能优化实战指南
  • Docker 入门教程(八):Dockerfile
  • MyBatis CRUD 常用动态 SQL 标签整理
  • ​19.自动补全功能
  • Swift 小技巧:用单边区间优雅处理模糊范围
  • 杨洋出席喜临门Ai净眠智能新品发布会 今夜无人失眠
  • 基于Java+Springboot的宠物健康咨询系统
  • tmux-copy mode相关配置文件
  • 小米路由器 AX3000T自定义子网掩码
  • rollupOptions 详细讲解,如何优化性能
  • 07-Seq2Seq英译法案例
  • 模运算优化