网问答>>C语言学习Day21
问题
已解决

C语言学习Day21

时间:2026-03-31 02:32:15
C语言学习Day21
最佳回答
在C语言中,字符串操作是核心内容之一。以下是对你提供的课程资料中关于字符串函数strcpy、strcat以及字符串搜索函数的详细解析和示例代码的优化说明。1. 字符串函数 strcpy功能:将源字符串 src 拷贝到目标字符串 dst 中。原型:char *strcpy(char *restrict dst, const char *restrict src);restrict 关键字表明 src 和 dst 不重叠(C99标准)。函数返回 dst 的指针,以便链式调用。示例代码优化:使用数组遍历的实现:#include stdio.h#include string.hchar* mycpy(char* dst, const char* src) { int idx = 0; while (src[idx]) { dst[idx] = src[idx]; idx++; } dst[idx] = 0; // 确保字符串以 null 结尾 return dst;}int main() { char s1[] = "abc"; char s2[] = "def"; mycpy(s1, s2); printf("%sn", s1); // 输出: def return 0;}使用指针的实现:#include stdio.h#include string.hchar* mycpy(char* dst, const char* src) { char* ret = dst; while ((*dst++ = *src++)) { ; // 空循环,依赖赋值表达式的值 } return ret;}int main() { char s1[] = "abc"; char s2[] = "def"; mycpy(s1, s2); printf("%sn", s1); // 输出: def return 0;}注意:目标字符串 dst 必须有足够的空间来容纳源字符串 src,包括终止符 0。使用 malloc 动态分配内存时,需确保分配的空间足够大(strlen(src) + 1)。2. 字符串函数 strcat功能:将源字符串 src 追加到目标字符串 dst 的末尾。原型:char *strcat(char *restrict s1, const char *restrict s2);返回 s1 的指针。s1 必须有足够的空间来容纳拼接后的字符串。示例代码:#include stdio.h#include string.hint main() { char s1[20] = "Hello, "; char s2[] = "world!"; strcat(s1, s2); printf("%sn", s1); // 输出: Hello, world! return 0;}安全问题:strcpy 和 strcat 可能导致缓冲区溢出。推荐使用安全版本:strncpy:限制拷贝的字符数。strncat:限制追加的字符数。安全版本示例:#include stdio.h#include string.hint main() { char s1[20] = "Hello, "; char s2[] = "world!"; strncat(s1, s2, sizeof(s1) - strlen(s1) - 1); printf("%sn", s1); // 输出: Hello, world! return 0;}3. 字符串搜索函数查找字符:strchr:查找字符串中第一次出现指定字符的位置。strrchr:查找字符串中最后一次出现指定字符的位置。原型:char *strchr(const char *s, int c);char *strrchr(const char *s, int c);返回指向找到字符的指针,未找到则返回 NULL。示例代码:#include stdio.h#include string.hint main() { const char *str = "Hello, world!"; char *p = strchr(str, o); if (p) { printf("First o at position: %ldn", p - str); // 输出: 4 } p = strrchr(str, o); if (p) { printf("Last o at
时间:2026-03-31 02:32:20
本类最有帮助
Copyright © 2008-2013 www.wangwenda.com All rights reserved.冀ICP备12000710号-1
投诉邮箱: