一、C length函數頭文件
C++的 string 類是 C++ 標準中用於處理字元串的最主要的類之一。C++ 的 string類 中包含了許多方便的函數,以幫助我們方便地進行字元串的處理。其中,length() 函數是 string 類中的一個重要函數。
在使用 length() 函數時,我們需要引入頭文件 string.h 或者 cstring。通過這些頭文件,我們可以使用字元串處理函數庫中定義的函數,如 strlen()、strcpy()、strcat()、strcmp() 等。
二、C length函數用法
C++ 標準庫中的 string 類對象可以通過使用 length() 函數來計算字元串的長度。
#include #include using namespace std; int main() { string str1 = "Hello, World!"; cout << "Length of string is : " << str1.length(); cout << endl; return 0; }
運行上面的代碼,我們可以得到以下輸出:
Length of string is : 13
這裡,我們定義了一個 string 類型的變數 str1,並將其初始化為 “Hello, World!”。然後,我們利用 length() 函數計算了該字元串的長度。輸出結果為 13,與該字元串的長度相等。
三、C length函數d, clength函數, c length函數 數組的長度
C++ 中還有其他函數可以用於計算字元串的長度。
在 C 語言中,strlen() 函數是計算字元串長度的標準函數,並且其返回值的類型為 size_t。它在頭文件 string.h 或 cstring 中被聲明。C++ 中的 length() 函數與 strlen() 函數不同,前者是 string 類下的函數,後者是 C 語言中的函數。
#include #include using namespace std; int main() { char str1[12] = "Hello"; char str2[12] = "World"; char str3[12]; int len ; /* 複製 str1 到 str3 */ strcpy( str3, str1); cout << "strcpy( str3, str1) : " << str3 << endl; /* 連接 str1 和 str2 */ strcat( str1, str2); cout << "strcat( str1, str2): " << str1 << endl; /* 連接後,str1 的總長度 */ len = strlen(str1); cout << "strlen(str1) : " << len << endl; return 0; }
上述代碼中,我們定義了三個 char 類型的字元串,並且使用了 strcpy() 和 strcat() 函數將它們複製和連接。然後,我們用 strlen() 函數分別計算了 str1 與 str2 相連後的字元串長度。
四、C函數 int, 函數len
除了 string 類和 C 語言中的函數,C++ 標準庫還提供了一些其他的函數,可以用於計算字元串長度。
比如,我們可以使用 cctype 頭文件中的函數 int ispunct ( int c ) 來計算一個字元串中的標點符號數,並用字元串總長度減去標點符號數,就可以得到字元串中字元數。
#include #include #include // 包含cctype頭文件用於計算標點符號 using namespace std; int main() { string str = "hello 123 ., world?"; int length = str.length(); int punct_count = 0; for (int i = 0; i < length; i++) { if (ispunct(str[i])) { punct_count++; } } int char_count = length - punct_count; cout << "The length of string is : " << char_count << endl; return 0; }
上述代碼中,我們使用了 string 類型的變數 str 以及 cctype 頭文件中的 ispunct() 函數、計算字元串總長度以及字元數的方法。運行該程序,我們將得到以下輸出:
The length of string is : 19
五、C函數…參數, LENGTH函數
在一些特殊情況下,我們可能需要使用變參函數來計算字元串長度。在 C++ 中,可以使用 … 參數以及 LENGTH 函數來實現這一目的。
#include #include using namespace std; int len(const char* format, ...) { va_list args; va_start(args, format); int count = vsnprintf(NULL, 0, format, args); va_end(args); return count; } int main() { cout << len("Hello %s", "World!") << endl; return 0; }
上述代碼中,我們定義了 len() 函數,它包含了一個 … 參數。然後,我們使用 vsnprintf() 函數計算字元串長度。
vsnprintf() 函數是可變參數選擇,具體說明請見函數文檔,一般用於將格式化字元串寫入字元數組。
運行上述程序,我們將獲得以下輸出:
Hello World!
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/195808.html