C 语言中的计数函数28
在 C 语言中,我们可以使用多个内置函数来计算数组或字符串中特定元素或字符的出现次数。这些函数提供了方便的方法来检查值的频率,这在各种编程场景中很有用。
strchr() 函数
strchr() 函数用于在字符串中搜索首次出现的特定字符。如果找到该字符,它将返回指向该字符的指针;否则,它将返回 NULL。
#include
int main() {
char str[] = "Hello World";
char *ptr = strchr(str, 'W');
if (ptr != NULL) {
printf("字符 'W' 出现在字符串中");
} else {
printf("字符串中不包含字符 'W'");
}
return 0;
}
strrchr() 函数
strrchr() 函数与 strchr() 函数类似,但它从字符串的末尾开始搜索特定字符。它返回指向该字符的指针,如果找不到,则返回 NULL。
#include
int main() {
char str[] = "Hello World";
char *ptr = strrchr(str, 'd');
if (ptr != NULL) {
printf("字符 'd' 出现在字符串中");
} else {
printf("字符串中不包含字符 'd'");
}
return 0;
}
strstr() 函数
strstr() 函数用于在字符串中搜索首次出现的子字符串。如果找到该子字符串,它将返回指向子字符串的指针;否则,它将返回 NULL。
#include
int main() {
char str[] = "Hello World";
char *ptr = strstr(str, "World");
if (ptr != NULL) {
printf("子字符串 'World' 出现在字符串中");
} else {
printf("字符串中不包含子字符串 'World'");
}
return 0;
}
strspn() 函数
strspn() 函数用于计算字符串中连续字符与给定子字符串匹配的长度。它返回匹配字符的长度。
#include
int main() {
char str[] = "Hello World";
int len = strspn(str, "Hello");
printf("匹配子字符串 'Hello' 的长度:%d", len);
return 0;
}
strcspn() 函数
strcspn() 函数与 strspn() 函数相反,它计算字符串中连续字符不与给定子字符串匹配的长度。它返回不匹配字符的长度。
#include
int main() {
char str[] = "Hello World";
int len = strcspn(str, "XYZ");
printf("不匹配子字符串 'XYZ' 的长度:%d", len);
return 0;
}
strlen() 函数
strlen() 函数计算字符串的长度,直到遇到空字符 ('\0')。
#include
int main() {
char str[] = "Hello World";
int len = strlen(str);
printf("字符串 'Hello World' 的长度:%d", len);
return 0;
}
calloc() 函数
calloc() 函数用于分配一段内存,并将其初始化为零。它返回指向分配内存的指针。我们可以使用此函数来创建数组并将其元素初始化为零。
#include
int main() {
int *arr = (int *)calloc(10, sizeof(int));
// 数组元素现在都为零
free(arr);
return 0;
}
malloc() 函数
malloc() 函数用于分配一段内存。它返回指向分配内存的指针。与 calloc() 不同,它不会初始化为零。我们需要手动初始化它。
#include
int main() {
int *arr = (int *)malloc(10 * sizeof(int));
// 需要手动初始化数组元素
free(arr);
return 0;
}
realloc() 函数
realloc() 函数用于重新分配一段内存。它可以增加或减少先前分配内存的大小。它返回指向重新分配内存的指针。如果内存不能被重新分配,则它返回 NULL。
#include
int main() {
int *arr = (int *)malloc(10 * sizeof(int));
// 重新分配内存以增加大小
arr = realloc(arr, 20 * sizeof(int));
free(arr);
return 0;
}
free() 函数
free() 函数用于释放先前通过 malloc()、calloc() 或 realloc() 分配的内存。它将内存返回给系统。
#include
int main() {
int *arr = (int *)malloc(10 * sizeof(int));
// 释放内存
free(arr);
return 0;
}
通过使用这些内置函数,我们可以轻松地计算数组或字符串中特定元素或字符的出现次数,从而简化各种编程任务。
2024-12-04
下一篇:C 语言中自定义输出值的终极指南
C语言输出深度解析:从控制台到文件与内存的精确定位与格式化
https://www.shuihudhg.cn/134466.html
Python高效解析与分析海量日志文件:性能优化与实战指南
https://www.shuihudhg.cn/134465.html
Java实时数据接收:从Socket到消息队列与Webhooks的全面指南
https://www.shuihudhg.cn/134464.html
PHP与MySQL:高效存储与操作JSON字符串的完整指南
https://www.shuihudhg.cn/134463.html
Python文本文件操作:从基础读写到高级管理与路径处理
https://www.shuihudhg.cn/134462.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