本文介紹如何計算字符串長度,共介紹三種方法,分別用length(), size(), strlen()
實現
length()介紹
利用length()
函數時,直接用字符串調用函數即可,格式如下:
string.length()
舉例:
#include<iostream>
using namespace std;
int main() {
string str = "CSDN";
cout << str.length() << endl; //輸出:4
system("pause");
return 0;
}
size()介紹
利用size()
函數時,同樣直接用字符串調用函數即可,格式如下:
string.size()
舉例:
#include<iostream>
using namespace std;
int main() {
string str = "CSDN";
cout << str.size() << endl; //輸出:4
system("pause");
return 0;
}
strlen()介紹
strlen()
函數計算字符串 str
的長度,直到空結束字符,但不包括空結束字符。
函數聲明如下:
size_t strlen(const char *str)
注意strlen()
函數的參數類型爲const char *
類型。
舉例:
#include<iostream>
using namespace std;
int main() {
const char* test;
test = "CSDN";
cout << test << endl; //輸出:CSDN
cout << strlen(test) << endl; //輸出:4
system("pause");
return 0;
}