C++中查詢字串長度的五種不同方法?


一系列字元或字元的線性陣列稱為字串。它的宣告與定義其他陣列相同。

陣列的長度是字串中字元的數量。有很多內建方法和其他方法可以查詢字串的長度。在這裡,我們將討論在 C++ 中查詢字串長度的五種不同方法。

1) 使用 C 的 strlen() 方法 - 此函式返回 C 的整數值。為此,您需要以字元陣列的形式傳遞字串。

使用 strlen() 方法的示例程式

#include <iostream>
#include <cstring>
using namespace std;
int main() {
   char charr[] = "I Love Tutorialspoint";
   int length = strlen(charr);
   cout << "the length of the character array is " << length;
   return 0;
}

輸出

the length of the character array is 21

2) 使用 c++ 的 size() 方法 - 它包含在 C++ 的字串庫中。返回字串中字元數量的整數值。

使用 size() 方法的示例程式

#include <iostream>
#include <string>
using namespace std;
int main() {
   string str = "I love tutorialspoint";
   int length = str.size();
   cout << "the length of the string is " << length;
   return 0;
}

輸出

The length of the string is 21

3) 使用 for 迴圈 - 此方法不需要任何函式。它遍歷陣列並計算其中的元素數量。迴圈執行直到遇到“/0”。

使用 for 迴圈查詢長度的程式

#include <iostream>
#include <string>
using namespace std;
int main() {
   string str = "I love tutorialspoint";
   int i;
   for(i=0; str[i]!='\0'; i++){ }
      cout << "the length of the string is " << i;
   return 0;
}

輸出

The length of the string is 21

4) 使用 length() 方法 - 在 C++ 中,字串庫中有一個 length() 方法,它返回字串中字元的數量。

使用 length() 方法查詢字串中字元數量的程式

#include <iostream>
#include <string>
using namespace std;
int main() {
   string str = "I love tutorialspoint";
   int length = str.length();
   cout << "the length of the string is " << length;
      return 0;
}

輸出

The length of the string is 21

5) 使用 while 迴圈查詢字串長度 - 您也可以使用 while 迴圈來計算字串中字元的數量。要計算字元的數量,您必須在 while 迴圈中使用計數器,並將結束條件指定為 != ‘\0’ 用於字串。

使用 while 迴圈查詢字串長度的程式

#include <iostream>
#include <string>
using namespace std;
int main() {
   string str = "I love tutorialspoint";
   int length = 0;
   while(str[length] !='\0' ){
      length++;
   }
   cout<<"The length of the string is "<< length;
   return 0;
}

輸出

The length of the string is 21

更新於:2019年8月8日

2K+ 次瀏覽

啟動你的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.