C++_統計字符串中英文字母、空格、數字和其它字符的個數

僞碼:

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;

}

 

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