neuq oj 1009C++統計字符 C++

統計字符

題目描述

輸入一行字符,分別統計出其中英文字母、空格、數字和其它字符的個數。

輸入

輸出

樣例輸入

a 1,

樣例輸出

1
1
1
1

代碼

#include<iostream>
using namespace std;
#define MAXSIZE 100

int engcount(string str)
{
    int i=0,eng=0;
    while(str[i]!='\0')
    {
        if((str[i]>='A'&&str[i]<='Z')||(str[i]>='a'&&str[i]<='z'))
        eng++;
        i++;
    }
    return eng;
}

int blacount(string str)
{
    int i=0,bla=0;
    while(str[i]!='\0')
    {
        if((str[i]==' '))
        bla++;
        i++;
    }
    return bla;
}

int numcount(string str)
{
    int i=0,num=0;
    while(str[i]!='\0')
    {
        if((str[i]>='0'&&str[i]<='9'))
        num++;
        i++;
    }
    return num;
}

int othcount(string str)
{
    int i=0;
    int e,b,n;
    int oth;
    e=engcount(str);
    b=blacount(str);
    n=numcount(str);
    while(str[i]!='\0')
    i++;
    oth=i-e-b-n;
    return oth;
}

int main()
{
	char str[MAXSIZE];
	gets(str);
	int eng,bla,num,oth;
        eng=engcount(str);
        bla=blacount(str);
	num=numcount(str);
	oth=othcount(str);
	cout<<"英文字母個數爲"<<eng<<endl;
	cout<<"空格個數爲"<<bla<<endl;
	cout<<"數字個數爲"<<num<<endl;
	cout<<"其它字符個數爲"<<oth<<endl;

	return 0;

}


體會:
gets()函數用來從標準輸入設備(鍵盤)讀取字符串直到換行符結束,但換行符會被丟棄,然後在末尾添加'\0'字符。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章