C++常用的長度計算方法size()、sizeof() 、strlen()、length()
- size():計算長度,std::string類的成員函數(shù)
- length():計算長度,std::string類的成員函數(shù)
- sizeof():計算所占用空間的字節(jié)數(shù),是運算符;在編譯時計算,獲得保證能容納實現(xiàn)所建立的最大對象的字節(jié)大小,因此sizeof不能用來返回動態(tài)分配的內存空間的大小
- strlen():需要包含頭文件cstring或string.h,輸入類型位char*
string 頭文件
#include <string> //C++標準庫頭文件
//<cstring>是C標準庫頭文件<string.h>對應的C++標準庫版本,如果使用strcmp、strchr、strstr、strlen等函數(shù),需要該頭文件
#include <cstring>
#include <string.h>
std::string長度計算
#include <iostream>
#include <string>
//#include <cstring>
#include <string.h>
int main(int argc, char *argv[])
{
std::string str_t = "condition";
std::cout<<str_t.size()<<std::endl;
std::cout<<str_t.length()<<std::endl;
std::cout<<sizeof(str_t)<<std::endl; //計算的不是長度
std::cout<<strlen(str_t.c_str())<<std::endl;
return 0;
}
輸出文章來源:http://www.zghlxwxcb.cn/news/detail-515947.html
9
9
32
9
char*長度計算
#include <iostream>
#include <string>
//#include <cstring>
#include <string.h>
int main(int argc, char *argv[])
{
char ch_t[]={"condition"};
char* pch = ch_t;
std::cout<<strlen(pch)<<std::endl;
std::cout<<sizeof(pch)<<std::endl;
return 0;
}
輸出文章來源地址http://www.zghlxwxcb.cn/news/detail-515947.html
9
8
到了這里,關于C++ 字符串長度計算的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!