C 标准库 - <string.h>学习笔记

简介

<string.h> 是 C 语言标准库中的一部分,它提供了一些与字符串操作相关的函数。

函数列表

以下是一些常用的 <string.h> 函数:

函数 描述
strcpy 复制字符串
strcat 连接两个字符串
strlen 返回字符串的长度
strcmp 比较两个字符串是否相等
strchr 在字符串中查找一个字符
strstr 在字符串中查找一个子串
memset 将一段内存设置为某个值
memcpy 将一段内存复制到另一个位置
memcmp 比较两段内存是否相等
memmove 将一段内存复制到另一个位置,可以处理重叠区域的内存复制操作

实例演示

以下是一些 <string.h> 函数的使用示例:

strcpy

cCopy Code
#include <stdio.h> #include <string.h> int main() { char str1[10] = "hello"; char str2[10]; // 复制 str1 到 str2 strcpy(str2, str1); printf("str1: %s\n", str1); // 输出: str1: hello printf("str2: %s\n", str2); // 输出: str2: hello return 0; }

strcat

cCopy Code
#include <stdio.h> #include <string.h> int main() { char str1[10] = "hello"; char str2[10] = "world"; // 将 str2 连接到 str1 的末尾 strcat(str1, str2); printf("str1: %s\n", str1); // 输出: str1: helloworld return 0; }

strlen

cCopy Code
#include <stdio.h> #include <string.h> int main() { char str[10] = "hello"; // 返回字符串的长度 printf("str length: %d\n", strlen(str)); // 输出: str length: 5 return 0; }

strcmp

cCopy Code
#include <stdio.h> #include <string.h> int main() { char str1[10] = "hello"; char str2[10] = "world"; // 比较两个字符串是否相等 if (strcmp(str1, str2) == 0) { printf("str1 和 str2 相等\n"); } else { printf("str1 和 str2 不相等\n"); } return 0; }

strchr

cCopy Code
#include <stdio.h> #include <string.h> int main() { char str[10] = "hello"; char *ptr; // 在 str 中查找字符 'e' ptr = strchr(str, 'e'); printf("ptr: %s\n", ptr); // 输出: ptr: ello return 0; }

strstr

cCopy Code
#include <stdio.h> #include <string.h> int main() { char str[10] = "hello"; char *ptr; // 在 str 中查找子串 'll' ptr = strstr(str, "ll"); printf("ptr: %s\n", ptr); // 输出: ptr: llo return 0; }

memset

cCopy Code
#include <stdio.h> #include <string.h> int main() { char str[10]; // 将 str 的前 5 个字符设置为字符 'a' memset(str, 'a', 5); printf("str: %s\n", str); // 输出: str: aaaaa return 0; }

memcpy

cCopy Code
#include <stdio.h> #include <string.h> int main() { char str1[10] = "hello"; char str2[10]; // 将 str1 复制到 str2 memcpy(str2, str1, strlen(str1) + 1); printf("str2: %s\n", str2); // 输出: str2: hello return 0; }

memcmp

cCopy Code
#include <stdio.h> #include <string.h> int main() { char str1[10] = "hello"; char str2[10] = "world"; // 比较两段内存是否相等 if (memcmp(str1, str2, strlen(str1)) == 0) { printf("str1 和 str2 相等\n"); } else { printf("str1 和 str2 不相等\n"); } return 0; }

memmove

cCopy Code
#include <stdio.h> #include <string.h> int main() { char str[10] = "hello world"; // 将 str 中的前 5 个字符移动到末尾 memmove(str + 5, str, strlen(str) - 5); printf("str: %s\n", str); // 输出: str: world hello return 0; }

总结

<string.h> 中的函数虽然看似简单,但是在实际的编程中却经常会用到。对于字符串相关的操作,这些函数能够提供高效且可靠的解决方案。熟练掌握它们的使用可以帮助我们更加轻松地完成任务。