編寫一個函數,由實參傳來一個字符串,統計此字符串中字母、數字、空格和其他字符的個數,在主函數中輸人字符串以及輸出上述的結果


編寫一個函數,由實參傳來一個字符串,統計此字符串中字母、數字、空格和其他字符的個數,在主函數中輸人字符串以及輸出上述的結果

題目解析:

該題的關鍵在於要能夠寫出各種字符統計的條件

代碼示例:

#include<stdio.h>

int letter, digit, space, others;

void CountChar(char str[])
{
	int i;
	for (i = 0; str[i] != '\0'; i++)
	{
        //統計字母
		if ((str[i] >= 'a'&& str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z')) 
			letter++;
		else if (str[i] >= '0' && str[i] <= '9') //統計數字
			digit++;
		else if (str[i] == ' ')//統計空格
			space++;
		else
			others++;  //統計其他字符
	}
}

int main()
{
	char text[80];
	printf("input string:\n");
	gets(text);
	printf("string: %s\n", text);

	CountChar(text);
	printf("\nletter:%d\ndigit:%d\nspace:%d\nothers:%d\n", letter, digit, space, others);
	return 0;
}

運行結果:

編寫一個函數,由實參傳來一個字符串,統計此字符串中字母、數字、空格和其他字符的個數,在主函數中輸人字符串以及輸出上述的結果


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM