字符串的長(zhǎng)度通常是指字符串中包含字符的數(shù)目,但有的時(shí)候人們需要的是字符串所占字節(jié)的數(shù)目。常見的獲取字符串長(zhǎng)度的方法包括如下幾種。
1.使用sizeof獲取字符串長(zhǎng)度sizeof的含義很明確,它用以獲取字符數(shù)組的字節(jié)數(shù)(當(dāng)然包括結(jié)束符\0)。對(duì)于ANSI字符串和UNICODE字符串,形式如下:
sizeof(cs)/sizeof(char)
sizeof(ws)/sizeof(wchar_t)
可以采用類似的方式,獲取到其字符的數(shù)目。如果遇到MBCS,如"中文ABC",很顯然,這種辦法就無法奏效了,因?yàn)閟izeof()并不知道哪個(gè)char是半個(gè)字符。
2.使用strlen()獲取字符串長(zhǎng)度strlen()及wcslen()是標(biāo)準(zhǔn)C++定義的函數(shù),它們分別獲取ASCII字符串及寬字符串的長(zhǎng)度,如:
size_t strlen( const char *string );
size_t wcslen( const wchar_t *string );
strlen()與wcslen()采取\0作為字符串的結(jié)束符,并返回不包括\0在內(nèi)的字符數(shù)目。
3.使用CString::GetLength()獲取字符串長(zhǎng)度CStringT繼承于CSimpleStringT類,該類具有函數(shù):
int GetLength( ) const throw( );
GetLength()返回字符而非字節(jié)的數(shù)目。比如:CStringW中,"中文ABC"的GetLength()會(huì)返回5,而非10。那么對(duì)于MBCS呢?同樣,它也只能將一個(gè)字節(jié)當(dāng)做一個(gè)字符,CStringA表示的"中文ABC"的GetLength()則會(huì)返回7。
4.使用std::string::size()獲取字符串長(zhǎng)度
basic_string同樣具有獲取大小的函數(shù):
size_type length( ) const;
size_type size( ) const;
length()和size()的功能完全一樣,它們僅僅返回字符而非字節(jié)的個(gè)數(shù)。如果遇到MCBS,它的表現(xiàn)和CStringA::GetLength()一樣。
5.使用_bstr_t::length()獲取字符串長(zhǎng)度_bstr_t類的length()方法也許是獲取字符數(shù)目的最佳方案,嚴(yán)格意義來講,_bstr_t還稱不上一個(gè)完善的字符串類,它主要提供了對(duì)BSTR類型的封裝,基本上沒幾個(gè)字符串操作的函數(shù)。不過,_bstr_t 提供了length()函數(shù):
unsigned int length ( ) const throw( );
該函數(shù)返回字符的數(shù)目。值得稱道的是,對(duì)于MBCS字符串,它會(huì)返回真正的字符數(shù)目。
現(xiàn)在動(dòng)手
編寫如下程序,體驗(yàn)獲取字符串長(zhǎng)度的各種方法。
【程序4-8】各種獲取字符串長(zhǎng)度的方法
01 #include "stdafx.h"
02 #include "string"
03 #include "comutil.h" 04 #pragma comment( lib, "comsuppw.lib" )
05
06 using namespace std;
07
08 int main()
09 {
10 char s1[] = "中文ABC";
11 wchar_t s2[] = L"中文ABC";
12
13 //使用sizeof獲取字符串長(zhǎng)度
14 printf("sizeof s1: %d\r\n", sizeof(s1)); 15 printf("sizeof s2: %d\r\n", sizeof(s2));
16
17 //使用strlen獲取字符串長(zhǎng)度
18 printf("strlen(s1): %d\r\n", strlen(s1)); 19 printf("wcslen(s2): %d\r\n", wcslen(s2));
20
21 //使用CString::GetLength()獲取字符串長(zhǎng)度
22 CStringA sa = s1;
23 CStringW sw = s2;
24
25 printf("sa.GetLength(): %d\r\n", sa.GetLength()); 26 printf("sw.GetLength(): %d\r\n", sw.GetLength());
27
28 //使用string::size()獲取字符串長(zhǎng)度
29 string ss1 = s1;
30 wstring ss2 = s2;
31
32 printf("ss1.size(): %d\r\n", ss1.size()); 33 printf("ss2.size(): %d\r\n", ss2.size());
34
35 //使用_bstr_t::length()獲取字符串長(zhǎng)度
36 _bstr_t bs1(s1);
37 _bstr_t bs2(s2);
38
39 printf("bs1.length(): %d\r\n", bs1.length()); 40 printf("bs2.length(): %d\r\n", bs2.length());
41
42 return 0;
43 }
輸出結(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
聯(lián)系客服