当前位置: 首页 > 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;
}
http://www.lqws.cn/news/567217.html

相关文章:

  • 量子算法入门——5.Qiskit库介绍与简单应用(2)
  • Ubuntu服务器(公网)- Ubuntu客户端(内网)的FRP内网穿透配置教程
  • 博图SCL编程利器:CASE OF 语句详解与应用指南之设备运行模式选择框架
  • 领域驱动设计(DDD)【28】之实践或推广DDD的学习
  • docker compose基本使用以及示例
  • 基于springboot+vue的数字科技风险报告管理系统
  • URL带有中文会引入哪些问题
  • http相关网络问题面试怎么答
  • 算法-基础算法-递归算法(Python)
  • 第十二节:Vben Admin 最新 v5.0 (vben5) 快速入门 - 两种权限控制方式(附前后端代码)
  • Vue 3 Teleport 特性
  • DXYZ投资-ai公司
  • 左神算法之Zigzag方式打印矩阵
  • Java面试题031:一文深入了解MySQL(3)
  • Vivado关联Vscode
  • Rust标量、复合类型与自定义类型、第三方并发结构
  • 【软考--软件设计师】2025-05 我的选择题错题总结
  • ListExtension 扩展方法增加 转DataTable()方法
  • 商业行业项目创业计划书PPT模版
  • 什么是区块链的跨链操作?
  • 穿越时空的光
  • 详解快速排序
  • SRS流媒体服务器(8)源码分析之rtc/rtmp互相转码详解
  • 数据可视化 - 单子图
  • 第10章 数组和指针
  • 左神算法之螺旋打印
  • SQL Server从入门到项目实践(超值版)读书笔记 19
  • 从GPTs到Real智能体:目前常见的几种创建智能体方式
  • spring:BeanPostProcessor后置处理器介绍
  • 小米路由器 AX3000T自定义子网掩码