C 语言中 s 函数:字符串操作详解164
在 C 语言中,s 函数是一组标准库函数,用于处理字符串。这些函数提供了广泛的功能,从字符串比较和连接到格式化输出和转换。
字符串比较* strcmp(s1, s2):比较两个字符串 s1 和 s2,如果相等返回 0,否则返回非零值。
* strncmp(s1, s2, n):比较两个字符串的前 n 个字符,如果相等返回 0,否则返回非零值。
* strcasecmp(s1, s2):忽略大小写地比较两个字符串,如果相等返回 0,否则返回非零值。
* strncasecmp(s1, s2, n):忽略大小写地比较两个字符串的前 n 个字符,如果相等返回 0,否则返回非零值。
字符串连接和复制* strcat(s1, s2):将字符串 s2 连接到字符串 s1 的末尾。
* strncat(s1, s2, n):将字符串 s2 的前 n 个字符连接到字符串 s1 的末尾。
* strcpy(s1, s2):将字符串 s2 复制到字符串 s1 中,覆盖 s1 中的现有内容。
* strncpy(s1, s2, n):将字符串 s2 的前 n 个字符复制到字符串 s1 中,覆盖 s1 中的前 n 个字符。
格式化输出* sprintf(s, format, ...):将格式化数据写入字符串 s,其中 format 是一个格式化字符串,后面跟着要格式化的变量。
* snprintf(s, size, format, ...):与 sprintf 类似,但只会将最多 size 个字符写入 s。
转换* atoi(s):将字符串 s 转换为整型。
* atol(s):将字符串 s 转换为长整型。
* atof(s):将字符串 s 转换为双精度浮点数。
* strtol(s, endptr, base):将字符串 s 转换为整型,并允许指定进制和终止指针 endptr。
* strtoul(s, endptr, base):将字符串 s 转换为无符号长整型,并允许指定进制和终止指针 endptr。
* strtod(s, endptr):将字符串 s 转换为双精度浮点数,并允许指定终止指针 endptr。
其他函数* strlen(s):获取字符串 s 的长度(不包括终止符)。
* strchr(s, c):在字符串 s 中查找第一个出现字符 c 的位置。
* strrchr(s, c):在字符串 s 中查找最后一个出现字符 c 的位置。
* strstr(s1, s2):在字符串 s1 中查找子字符串 s2 的第一次出现。
* strtok(s, delim):将字符串 s 分割成一组字符串,使用指定的分隔符 delim。
示例下面是一个示例程序,展示了 s 函数的不同用法:
```c
#include
#include
int main() {
char s1[] = "Hello";
char s2[] = "World";
// 字符串比较
if (strcmp(s1, s2) == 0)
printf("s1 和 s2 相等");
else
printf("s1 和 s2 不相等");
// 字符串连接
strcat(s1, s2);
printf("连接后的字符串:%s", s1);
// 格式化输出
char buffer[50];
sprintf(buffer, "整数 %d", 123);
printf("格式化后的字符串:%s", buffer);
// 转换
int num = atoi("123");
printf("转换后的整数:%d", num);
return 0;
}
```
输出:
```
s1 和 s2 不相等
连接后的字符串:HelloWorld
格式化后的字符串:整数 123
转换后的整数:123
```
2024-11-06
上一篇:C 语言中的函数原型
Java方法栈日志的艺术:从错误定位到性能优化的深度指南
https://www.shuihudhg.cn/133725.html
PHP 获取本机端口的全面指南:实践与技巧
https://www.shuihudhg.cn/133724.html
Python内置函数:从核心原理到高级应用,精通Python编程的基石
https://www.shuihudhg.cn/133723.html
Java Stream转数组:从基础到高级,掌握高性能数据转换的艺术
https://www.shuihudhg.cn/133722.html
深入解析:基于Java数组构建简易ATM机系统,从原理到代码实践
https://www.shuihudhg.cn/133721.html
热门文章
C 语言中实现正序输出
https://www.shuihudhg.cn/2788.html
c语言选择排序算法详解
https://www.shuihudhg.cn/45804.html
C 语言函数:定义与声明
https://www.shuihudhg.cn/5703.html
C语言中的开方函数:sqrt()
https://www.shuihudhg.cn/347.html
C 语言中字符串输出的全面指南
https://www.shuihudhg.cn/4366.html