本题要求实现一个函数,统计给定字符串中英文字母、空格或回车、数字字符和其他字符的个数。
- 小知识:
c语言'\0' 意思:
字符常量占一个字节的内存空间。字du符串常量占的内存字节数zhi等于字符串中dao字节数加1。增加的一个字节中存放字符"\0" (ASCII码为0)。这是字符串结束的标志。
所以原来的这块:
int n = strlen(s);
for (int i = 0; i < n ; i ++ )
就可以改成:
for (int i = 0; s[i] != '\0' ; i ++ )
- code
#include <stdio.h>
#include <string.h>
#define MAXS 15
void StringCount( char s[] )
{
int letter = 0, blank = 0, digit = 0, other = 0;
int n = strlen(s);
for (int i = 0; i < n ; i ++ )
{
if(s[i] >= '0' && s[i] <= '9') digit += 1;
else if (s[i] == ' ' || s[i] == '\n') blank += 1;
else if ( (s[i] >= 'a' && s[i] <= 'z') || (s[i] >= 'a' && s[i] <= 'z')) letter += 1;
else other += 1;
}
printf("letter = %d, blank = %d, digit = %d, other = %d", letter, blank, digit, other);
}
void ReadString( char s[] ); /* 由裁判实现,略去不表 */
int main()
{
char s[MAXS];
ReadString(s);
StringCount(s);
return 0;
}
/* Your function will be put here */