目录
[1. strcpy 函数](#1. strcpy 函数)
[2. strncpy 函数](#2. strncpy 函数)
[3. strcat 函数](#3. strcat 函数)
[4. strncat 函数](#4. strncat 函数)
[5. strcmp 函数](#5. strcmp 函数)
[6. strncmp 函数](#6. strncmp 函数)
C语言核心:字符串处理函数与递归函数详解
一、字符串处理函数族
C语言提供了一系列强大的字符串处理函数,这些函数定义在 <string.h> 头文件中,能够高效地完成字符串复制、拼接和比较等操作。
1. strcpy 函数
c
#include <stdio.h>
#include <string.h>
int main() {
char src[20] = "Hello, World!";
char dest[20];
// 字符串复制
strcpy(dest, src);
printf("复制结果: %s\n", dest); // 输出: Hello, World!
return 0;
}
2. strncpy 函数
c
#include <stdio.h>
#include <string.h>
int main() {
char src[20] = "Hello, World!";
char dest[20] = {0}; // 初始化
// 安全复制前5个字符
strncpy(dest, src, 5);
printf("限定复制: %s\n", dest); // 输出: Hello
return 0;
}
3. strcat 函数
c
#include <stdio.h>
#include <string.h>
int main() {
char dest[30] = "Hello";
char src[15] = ", World!";
// 字符串拼接
strcat(dest, src);
printf("拼接结果: %s\n", dest); // 输出: Hello, World!
return 0;
}
4. strncat 函数
c
#include <stdio.h>
#include <string.h>
int main() {
char dest[20] = "Hello";
char src[15] = ", World!";
// 安全拼接前7个字符
strncat(dest, src, 7);
printf("限定拼接: %s\n", dest); // 输出: Hello, Wor
return 0;
}
5. strcmp 函数
c
#include <stdio.h>
#include <string.h>
int main() {
char s1[] = "apple";
char s2[] = "banana";
int result = strcmp(s1, s2);
printf("比较结果: %d\n", result); // 输出: -1 (负数表示s1 < s2)
return 0;
}
6. strncmp 函数
c
#include <stdio.h>
#include <string.h>
int main() {
char s1[] = "apple";
char s2[] = "application";
// 比较前3个字符
int result = strncmp(s1, s2, 3);
printf("限定比较: %d\n", result); // 输出: 0 (前3字符相同)
return 0;
}
二、递归函数详解
递归是一种函数调用自身的编程技巧,包含两个关键阶段:递归阶段 (问题分解)和回归阶段(结果合并)。
案例1:数字逐位输出
c
#include <stdio.h>
void print_digits(int num) {
if (num > 9) {
print_digits(num / 10); // 递归阶段
}
printf("%d\n", num % 10); // 回归阶段
}
int main() {
int number = 1234;
print_digits(number);
return 0;
}
执行过程解析:
print_digits(1234)
├─ print_digits(123)
│ ├─ print_digits(12)
│ │ ├─ print_digits(1) → 输出 1
│ │ └─ 输出 2
│ └─ 输出 3
└─ 输出 4
案例2:阶乘计算
c
#include <stdio.h>
int factorial(int n) {
if (n == 0 || n == 1) // 终止条件
return 1;
return n * factorial(n - 1); // 递归调用
}
int main() {
int num = 5;
printf("%d! = %d\n", num, factorial(num)); // 输出: 120
return 0;
}
执行过程解析:
factorial(5)
= 5 * factorial(4)
= 5 * (4 * factorial(3))
= 5 * 4 * (3 * factorial(2))
= 5 * 4 * 3 * (2 * factorial(1))
= 5 * 4 * 3 * 2 * 1
= 120
三、关键注意事项
-
字符串安全:
- 使用
strncpy和strncat避免缓冲区溢出 - 目标数组大小需大于源字符串长度
- 使用
-
递归设计原则:
- 明确的终止条件
- 每次递归缩小问题规模
- 避免栈溢出(深度不宜超过10000层)
-
函数对比:
函数 功能 安全特性 strcpy完整复制 无长度检查 strncpy限定长度复制 自动补零 strcmp完整字符串比较 逐字符对比 strncmp限定长度比较 安全边界控制
通过本文学会合理使用字符串处理函数和递归技术,将大幅提升C语言编程效率和代码质量。建议读者在实际项目中多练习这些核心功能,加深理解。