在代碼中經常會求字符串的有效長度,對char型字符串數組大家會用strlen來求它的有效長度,如何求string類型字符串的有效長度呢?這裏有三種方法。
(1)使用string的成員函數length();
這裏獲取的即爲字符串的有效長度。
#define _CRT_SECURE_NO_WARNINGS
#include "iostream"
#include "string"
using namespace std;
int main()
{
string str = "hello world";
int len = str.length();
cout<<len<<endl;
system("pause");
return 0;
}
(2)使用string的成員函數size();
這裏size()表示string容器中有效元素的個數。以達到獲取字符串長度的目的。
#define _CRT_SECURE_NO_WARNINGS
#include "iostream"
#include "string"
using namespace std;
int main()
{
string str = "hello world";
int len = str.size();
cout<<len<<endl;
system("pause");
return 0;
}
(3)使用strlen函數;
不能直接使用strlen函數來獲取有效長度,需要先將string轉換爲char*類型,這裏需要用到c_str()函數。
#define _CRT_SECURE_NO_WARNINGS
#include "iostream"
#include "string"
using namespace std;
int main()
{
string str = "hello world";
int len = strlen(str.c_str());
cout<<len<<endl;
system("pause");
return 0;
}