更新時(shí)間:2020-11-05 17:37:35 來源:動(dòng)力節(jié)點(diǎn) 瀏覽1652次
字符串長度就是這個(gè)字符串所包含字符的個(gè)數(shù),但是這個(gè)長度是不包含 NUL 字符的。字符串長度通常是指字符串中包含字符的數(shù)目,但有的時(shí)候人們需要的是字符串所占字節(jié)的數(shù)目。事實(shí)上,求解字符串長度的方法不是單一的,而是靈活多變的。
下面我們先來看一下C++中關(guān)于字符串的定義:
#include
#include
int main()
{
char str1[] = "Hello World!";
printf("%d\n",strlen(str1));
return 0;
}
/* output:
* 12
*/
常見的獲取字符串長度的方法包括如下幾種。
1.strlen()
這個(gè)測字符數(shù)組長度,需要頭文件 #include
#include
#include
using namespace std;
main ()
{
char c[100005];
cin >> c;
int len = strlen(c);
cout << len << endl;
}
2.sizeof()
測所占內(nèi)存大小(就是在計(jì)算機(jī)中占幾個(gè)字節(jié))
#include
#include
using namespace std;
main ()
{
char c[100005];
cin >> c;
cout << "數(shù)組長度為" << endl;
int len = strlen(c);
cout << len << endl;
cout << "c數(shù)組占字節(jié)長度為" << endl;
int Csize = sizeof(c);
cout << Csize << endl;
}
3.s.length()
用來測 string 定義的類的字符串長度
#include
#include
#include
using namespace std;
main ()
{
string s;
cin >> s;
int len = s.length();
cout << len << endl;
int Ssize = sizeof(s);
cout << Ssize << endl;
}
4.s.size()
用來測 string 定義的類的字符串長度和s.length()一樣沒區(qū)別
#include
#include
#include
using namespace std;
main ()
{
string s;
cin >> s;
int len = s.size(); //長度
cout << len << endl;
int Ssize = sizeof(s); //所占空間的大小
cout << Ssize << endl;
}
編寫如下程序,體驗(yàn)獲取字符串長度的各種方法。
#include "stdafx.h"
#include "string"
#include "comutil.h"
#pragma comment( lib, "comsuppw.lib" )
using namespace std;
int main()
{
char s1[] = "中文ABC";
wchar_t s2[] = L"中文ABC";
//使用sizeof獲取字符串長度
printf("sizeof s1: %d\r\n", sizeof(s1));
printf("sizeof s2: %d\r\n", sizeof(s2));
//使用strlen獲取字符串長度
printf("strlen(s1): %d\r\n", strlen(s1));
printf("wcslen(s2): %d\r\n", wcslen(s2));
//使用CString::GetLength()獲取字符串長度
CStringA sa = s1;
CStringW sw = s2;
printf("sa.GetLength(): %d\r\n", sa.GetLength());
printf("sw.GetLength(): %d\r\n", sw.GetLength());
//使用string::size()獲取字符串長度
string ss1 = s1;
wstring ss2 = s2;
printf("ss1.size(): %d\r\n", ss1.size());
printf("ss2.size(): %d\r\n", ss2.size());
//使用_bstr_t::length()獲取字符串長度
_bstr_t bs1(s1);
_bstr_t bs2(s2);
printf("bs1.length(): %d\r\n", bs1.length());
printf("bs2.length(): %d\r\n", bs2.length());
return 0;
}
輸出結(jié)果:
sizeof s1: 8
sizeof s2: 12
strlen(s1): 7
wcslen(s2): 5
sa.GetLength(): 7
sw.GetLength(): 5
ss1.size(): 7
ss2.size(): 5
bs1.length(): 5
bs2.length(): 5
總之,4種求字符串長度的方式分別為strlen() ,sizeof() ,s.length() ,s.size()以上內(nèi)容詳細(xì)的介紹了求解字符串長度的4種方法以及實(shí)例說明,如果單靠個(gè)別例子無法理解如何求字符串長度,可以觀看本站的Java基礎(chǔ)教程,里面還有更多的詳細(xì)的實(shí)例講解,幫助你加深對字符串長度的理解。
初級 202925
初級 203221
初級 202629
初級 203743