C++_統計字串中英文字母、空格、數字和其它字元的個數
阿新 • • 發佈:2019-01-10
偽碼:
STATISTIC(letters, space, digit, others, c)
1. input(c)
2. letters<-0; space<-0; digit<-0; others<-0 //初始化變數值,letters-英文字母,space-空格,digit-數字,others-其他//
3. while ( c!=’\n’) do //統計各個型別字元數//
4. If(c>=’a’ AND c<=’z’ OR c>=’A’ AND z<=’Z’)
5. then letters<-letters+1
6. else if (c=’ ‘)
7. then space<-space+1
8. else if(c>=’0’ AND c<=’9’)
9. then digit<-digit+1
10. else others<-others+1
11. end(while)
12. output (letters, spaces, digit, others) //輸出結果//
13. return
測試用例:asdfdg 1234
測試結果:all in all: char=6 space=2 digit=4 others=0
源程式:
#include "iostream" using namespace std; int main() { char c; int letters=0,space=0,digit=0,others=0; cout<<"please input some characters"<<endl; while((c=getchar())!='\n') { if(c>='a'&&c<='z'||c>='A'&&c<='Z') letters++; else if(c==' ') space++; else if(c>='0'&&c<='9') digit++; else others++; } printf("all in all:char=%d space=%d digit=%d others=%d\n",letters,space,digit,others); system("pause"); return 0; }