C++ 程式查詢字串長度
字串是一維字元陣列,以空字元結尾。字串的長度是在空字元之前的字元數。
例如。
char str[] = “The sky is blue”; Number of characters in the above string = 15
查詢字串長度的程式如下所示。
示例
#include<iostream> using namespace std; int main() { char str[] = "Apple"; int count = 0; while (str[count] != '\0') count++; cout<<"The string is "<<str<<endl; cout <<"The length of the string is "<<count<<endl; return 0; }
輸出
The string is Apple The length of the string is 5
在上面的程式中,count 變數在 while 迴圈中遞增,直到在字串中遇到空字元。最後,count 變數儲存字串的長度。如下所示。
while (str[count] != '\0') count++;
獲得字串長度後,將其顯示在螢幕上。以下程式碼片段演示了這一點。
cout<<"The string is "<<str<<endl; cout<<"The length of the string is "<<count<<endl;
也可以使用 strlen() 函式查詢字串的長度。以下程式演示了這一點。
示例
#include<iostream> #include<string.h> using namespace std; int main() { char str[] = "Grapes are green"; int count = 0; cout<<"The string is "<<str<<endl; cout <<"The length of the string is "<<strlen(str); return 0; }
輸出
The string is Grapes are green The length of the string is 16
廣告