C语言字符串操作 #
一、字符串与数字转换 #
1.1 字符串转数字 #
c
#include <stdio.h>
#include <stdlib.h>
int main() {
printf("%d\n", atoi("123"));
printf("%ld\n", atol("123456"));
printf("%f\n", atof("3.14"));
return 0;
}
1.2 数字转字符串 #
c
#include <stdio.h>
int main() {
char buf[20];
sprintf(buf, "%d", 123);
printf("字符串: %s\n", buf);
return 0;
}
二、字符串分割 #
2.1 strtok #
c
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello,World,C";
char* token = strtok(str, ",");
while (token != NULL) {
printf("%s\n", token);
token = strtok(NULL, ",");
}
return 0;
}
三、字符串格式化 #
3.1 sprintf #
c
#include <stdio.h>
int main() {
char buf[100];
int a = 10, b = 20;
sprintf(buf, "%d + %d = %d", a, b, a + b);
printf("%s\n", buf);
return 0;
}
3.2 sscanf #
c
#include <stdio.h>
int main() {
char str[] = "10 20 30";
int a, b, c;
sscanf(str, "%d %d %d", &a, &b, &c);
printf("%d, %d, %d\n", a, b, c);
return 0;
}
四、大小写转换 #
4.1 转换函数 #
c
#include <stdio.h>
#include <ctype.h>
int main() {
char c = 'a';
printf("大写: %c\n", toupper(c));
printf("小写: %c\n", tolower('A'));
return 0;
}
五、总结 #
| 操作 | 函数 |
|---|---|
| 转数字 | atoi, atol, atof |
| 格式化 | sprintf, sscanf |
| 分割 | strtok |
| 大小写 | toupper, tolower |
下一步,让我们学习结构体!
最后更新:2026-03-26