c语言如何计算字符数量

655Z技术栈 C/C++编程 2025年07月24日 12

在C语言中,可以使用循环结构和条件语句来计算字符的数量。以下是一个示例代码:

#include <stdio.h> int main() { char str[100]; int count = 0; printf("请输入一个字符串:"); fgets(str, sizeof(str), stdin); // 从标准输入读取字符串 for(int i = 0; str[i] != '\0'; i++) { if(str[i] != ' ' && str[i] != '\n' && str[i] != '\t') { count++; } } printf("字符数量为:%d\n", count); return 0; }

在上述代码中,首先定义了一个字符串数组 str 和一个整型变量 count,用于存储输入的字符串和字符数量。

然后,通过调用 fgets 函数从标准输入读取字符串,并将其存储在 str 中。

接下来,使用 for 循环遍历整个字符串,当遇到非空格、换行符和制表符时,将计数器 count 的值加一。

最后,通过调用 printf 函数输出字符数量。

注意:上述代码中假设输入的字符串长度不超过100个字符。如果需要处理更长的字符串,可以相应地调整 str 数组的大小。

提供PHP及ThinkPHP框架的定制开发、代码优化,PHP修改、ThinkPHP修改。

邮箱:yvsm@163.com 微信:yvsm316 QQ:316430983
关闭

用微信“扫一扫”