C++ 字串長度



字串的長度是指字串中存在的字元數。這些字元可以是char資料型別,包括所有字母數字元素、符號和雜項字元。在C++程式語言中,有兩種型別的字串——C風格的字元陣列字串物件,它們是<string>類的內建物件。

字串的長度也包括空格,但是如果字串包含終止字元“\0”,則字串在此字元處結束,長度計數在此字元之前終止。

有很多方法可以找到給定字串的長度。其中一些方法是迭代的,而另一些方法也使用內建函式和方法。這些方法將在本章的後續部分中清楚地解釋:

  • 使用strlen()方法
  • 使用字串類的string::length()方法
  • 使用字串類的string::size()方法
  • 使用迭代for迴圈
  • 使用迭代while迴圈

使用 strlen() 方法計算字串長度

字串定義為字元陣列,可以使用指向陣列第一個迭代器的指標來訪問。我們可以使用C庫的strlen()方法來計算C型別陣列的長度。

語法

以下語法顯示瞭如何使用 strlen() 方法計算字串的長度:

strlen(string_name);

示例

以下示例演示瞭如何使用 strlen() 方法計算字串的長度:

#include <bits/stdc++.h>
using namespace std;

int main() {
   char s[]="I love TP !!!";
   cout<<"Length of string s : "<<strlen(s);
   return 0;
}

輸出

Length of string s : 13

使用 string::size() 方法計算字串長度

大多數程式設計師通常在需要計算C++程式語言中字串長度時使用字串類的string::size()方法。這是最基本的方法,通常在遍歷字串物件時使用。

語法

以下語法顯示瞭如何使用 size() 方法計算字串的長度:

string_object.size();

示例

以下示例演示瞭如何使用 size() 方法計算字串的長度:

#include <bits/stdc++.h>
using namespace std;

int main() {
   string s="I love TP !!!\0 and others";

   cout<<"Length of string s : "<<s.size();
   return 0;
}

輸出

Length of string s : 13

使用 string::length() 方法計算字串長度

我們還可以使用字串類的length()方法來確定給定字串的長度。length()size()方法都是<string>標頭檔案的一部分,它們被稱為字串物件的方法。

語法

以下語法顯示瞭如何使用 length() 方法計算字串的長度:

string_object.length();

示例

以下示例演示瞭如何使用 length() 方法計算字串的長度:

#include <bits/stdc++.h>
using namespace std;

int main() {
   string s="I love TP !!!\0 and others";

   cout<<"Length of string s : "<<s.length();
   return 0;
}

輸出

Length of string s : 13

使用 while 迴圈計算字串長度

我們可以使用簡單的while迴圈迭代字串並初始化一個變數計數器來計算字串的長度,直到到達字串的末尾。對於每次迭代,計數器增加一,因此最終結果將是字串的長度。

語法

以下語法顯示瞭如何使用while迴圈計算字串的長度:

while(s[i]!='\0') {
   [body]
}

示例

以下示例演示瞭如何使用單個 while 迴圈計算字串的長度:

#include <bits/stdc++.h>
using namespace std;

int main() {
   string s="I love TP !!!\0 and others";
   int count=0, i=0;
   while(s[i]!='\0') 
      count++, i++;

   cout<<"Length of string s : "<<count;
   return 0;
}

輸出

Length of string s : 13

使用 for 迴圈計算字串長度

我們可以使用簡單的for迴圈迭代字串並初始化一個變數計數器來計算字串的長度,直到到達字串的末尾。對於每次迭代,計數器增加一,因此最終結果將是字串的長度。

語法

以下語法顯示瞭如何使用 for 迴圈計算字串的長度:

for(int i=0;s[i]!='\0';i++){
   [body]
}

示例

以下示例演示瞭如何使用單個 for 迴圈計算字串的長度:

#include <bits/stdc++.h>
using namespace std;

int main() {
   string s="I love TP !!!\0 and others";
   int count=0;
   for(int i=0;s[i]!='\0';i++) 
      count++;

   cout<<"Length of string s : "<<count;
   return 0;
}

輸出

Length of string s : 13
廣告