Home >Backend Development >C#.Net Tutorial >C language counts the number of characters in a string

C language counts the number of characters in a string

王林
王林Original
2020-05-11 16:26:4117708browse

C language counts the number of characters in a string

Objective:

Enter a line of characters and count the number of various characters in it.

Specific code:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define M 1024
void main() {
	char str[M];
	fgets(str, M, stdin);
	int space = 0;
	int letter = 0;
	int num = 0;
	int other = 0;
	for (int i = 0; i < (int)strlen(str); ++i) {
		if (str[i] == &#39; &#39;) {
			space += 1;
		}
		else if (str[i] > 64 && str[i] < 91 || str[i]>96 && str[i] < 123)  {
			letter += 1;
		}
		else if (str[i] > 47 && str[i] < 58)  {
			num += 1;
		}
		else {
			if (str[i] != &#39;\n&#39;) {//因为fgets()函数会在末尾自动加上\n,影响判断结果,需要判断是否为换行符
				other += 1;
			}
		}
	}
	printf("空格的个数为:%d\n", space);
	printf("英文字母的个数为:%d\n", letter);
	printf("数字的个数为:%d\n", num);
	printf("其他字符的个数为:%d\n", other);
	system("pause");
}

Note: The fgets() function will read the carriage return character \n that we type on the keyboard at the end of the string (before \0).

The running results are as follows:

C language counts the number of characters in a string

Recommended tutorial: c language tutorial

The above is the detailed content of C language counts the number of characters in a string. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn