返回列表 發帖

字串處理 (六) - 取得字串長度 1

本帖最後由 tonyh 於 2021-6-26 20:04 編輯

設計一程式, 能計算使用者輸入的字串長度(有幾個字元)

  1. #include<iostream>
  2. #include<cstdlib>
  3. using namespace std;
  4. int main()
  5. {
  6.     int sum=0;
  7.     char str[50];
  8.     cout<<"輸入一字串: ";
  9.     cin.getline(str,50);
  10.     for(int i=0; str[i]!=NULL; i++)
  11.         sum++;
  12.     cout<<"本字串共包含: "<<sum<<" 個字元"<<endl;
  13.     system("pause");     
  14.     return 0;
  15. }
複製代碼
  1. #include<iostream>
  2. #include<cstdlib>
  3. #include<cstring>
  4. using namespace std;
  5. int main()
  6. {
  7.     int sum=0;
  8.     string str;
  9.     cout<<"請輸入一字串: ";
  10.     getline(cin, str);
  11.     while(true)
  12.     {
  13.         if(str[sum]==NULL)
  14.         {
  15.             cout<<"本字串的長度為"<<sum<<"個字元!"<<endl;
  16.             break;
  17.         }
  18.         sum++;      
  19.     }
  20.     system("pause");
  21.     return 0;   
  22. }
複製代碼

返回列表