檢查字串練習 (字數計算)

C++:
  1. #include <iostream.h>  // 引入標準輸入/輸出函數標題檔
  2. #include <string.h>    // 引入字串函數標題檔
  3. #include <ctype.h>     // 引入字元測試與轉換函數標題檔
  4.  
  5. int main()
  6. {
  7.   int print = 0, digit = 0, lower = 0, upper = 0;
  8.   int punct = 0, space = 0, control = 0, chinese = 0;
  9.   char string[] = "Elipse 是一個整合式的開發環境"
  10.  "(Integrated Development Environment;IDE),"
  11.  "它提供 C++、Java 與其他程式的開發環境。";
  12.   int len = strlen(string);          // 取得字串長度
  13.   for (int i = 0; i <= len; i++)     // 字元檢查迴圈
  14.   {
  15.     if (isprint(string[i]) != 0)     // 若為可列印字元
  16.     {
  17.       print++;
  18.       if (isdigit(string[i]) != 0)      // 為數字字元
  19.         digit++;
  20.       else if (islower(string[i]) != 0) // 為小寫字元
  21.         lower++;
  22.       else if (isupper(string[i]) != 0) // 為大寫字元
  23.         upper++;
  24.       else if (ispunct(string[i]) != 0) // 為符號字元
  25.         punct++;
  26.       else                            // 否則為空白字元
  27.         space++;
  28.     }
  29.     else if (iscntrl(string[i]) != 0)// 若為控制符號字元
  30.     {
  31.       control++;
  32.     }
  33.     else              // 否則為全形文字(中文)字元
  34.     {
  35.       chinese++;
  36.       i++;            // 全形字為2bytes,要多移一個字元
  37.     }
  38.   }
  39.   cout <<"英數符號字數:" <<print;            // 顯示訊息字串
  40.   cout <<"n  大寫字數:" <<upper;        // 顯示訊息字串
  41.   cout <<"n  小寫字數:" <<lower;         // 顯示訊息字串
  42.   cout <<"n  數字字數:" <<digit;           // 顯示訊息字串
  43.   cout <<"n  空白字數:" <<space;         // 顯示訊息字串
  44.   cout <<"n  符號字數:" <<punct;         // 顯示訊息字串
  45.   cout <<"n控制符號字數:" <<control;       // 顯示訊息字串
  46.   cout <<"n全形文字字數:" <<chinese;       // 顯示訊息字串
  47.   cout <<endl <<endl;
  48.   return 0;
  49. }

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 Bluelove1968 的頭像
    Bluelove1968

    藍色情懷

    Bluelove1968 發表在 痞客邦 留言(0) 人氣()