常⽤字符串长度计算函数
字符串的长度通常是指字符串中包含字符的数⽬,但有的时候⼈们需要的是字符串所占字节的数⽬。常见的获取字符串长度的⽅法包括如下⼏种。
1.使⽤sizeof获取字符串长度
sizeof的含义很明确,它⽤以获取字符数组的字节数(当然包括结束符\0)。对于ANSI字符串和UNICODE字符串,形式如下:
1. sizeof(cs)/sizeof(char)
2. sizeof(ws)/sizeof(wchar_t)
可以采⽤类似的⽅式,获取到其字符的数⽬。如果遇到MBCS,如"中⽂ABC",很显然,这种办法就⽆法奏效了,因为sizeof()并不知道哪个char是半个字符。
2.使⽤strlen()获取字符串长度
strlen()及wcslen()是标准C++定义的函数,它们分别获取ASCII字符串及宽字符串的长度,如:
1. size_t strlen( const char *string );
2. size_t wcslen( const wchar_t *string );
strlen()与wcslen()采取\0作为字符串的结束符,并返回不包括\0在内的字符数⽬。
3.使⽤CString::GetLength()获取字符串长度
CStringT继承于CSimpleStringT类,该类具有函数:
1. int GetLength( ) const throw( );
GetLength()返回字符⽽⾮字节的数⽬。⽐如:CStringW中,"中⽂ABC"的GetLength()会返回5,⽽⾮10。那么对于MBCS呢?同样,它也只能将⼀个字节当做⼀个字符,CStringA表⽰的"中⽂ABC"的GetLength()则会返回7。
4.使⽤std::string::size()获取字符串长度
basic_string同样具有获取⼤⼩的函数:
1. size_type length( ) const;
2. size_type size( ) const;
length()和size()的功能完全⼀样,它们仅仅返回字符⽽⾮字节的个数。如果遇到MCBS,它的表现和CStringA::GetLength()⼀样。5.使⽤_bstr_t::length()获取字符串长度
_bstr_t类的length()⽅法也许是获取字符数⽬的最佳⽅案,严格意义来讲,_bstr_t还称不上⼀个完善的字符串类,它主要提供了对BSTR类型的封装,基本上没⼏个字符串操作的函数。不过,_bstr_t 提供了length()函数:
1. unsigned int length ( ) const throw( );
该函数返回字符的数⽬。值得称道的是,对于MBCS字符串,它会返回真正的字符数⽬。
现在动⼿
编写如下程序,体验获取字符串长度的各种⽅法。
【程序 4-8】各种获取字符串长度的⽅法
1. 01  #include "stdafx.h"
2. 02  #include "string"
3. 03  #include "comutil.h"
4. 04  #pragma comment( lib, "comsuppw.lib" )
5. 05
6. 06  using namespace std;
7. 07
8. 08  int main()
9. 09  {
10. 10      char s1[] = "中⽂ABC";
11. 11      wchar_t s2[] = L"中⽂ABC";
12. 12
13. 13      //使⽤sizeof获取字符串长度
14. 14      printf("sizeof s1: %d\r\n", sizeof(s1));
15. 15      printf("sizeof s2: %d\r\n", sizeof(s2));
16. 16
17. 17      //使⽤strlen获取字符串长度
18. 18      printf("strlen(s1): %d\r\n", strlen(s1));
19. 19      printf("wcslen(s2): %d\r\n", wcslen(s2));
20. 20
21. 21      //使⽤CString::GetLength()获取字符串长度
22. 22      CStringA sa = s1;
23. 23      CStringW sw = s2;
24. 24
25. 25      printf("sa.GetLength(): %d\r\n", sa.GetLength());
26. 26      printf("sw.GetLength(): %d\r\n", sw.GetLength());
27. 27
28. 28      //使⽤string::size()获取字符串长度
29. 29      string ss1 = s1;
30. 30      wstring ss2 = s2;
31. 31
32. 32      printf("ss1.size(): %d\r\n", ss1.size());
33. 33      printf("ss2.size(): %d\r\n", ss2.size());
34. 34
35. 35      //使⽤_bstr_t::length()获取字符串长度
36. 36      _bstr_t bs1(s1);
37. 37      _bstr_t bs2(s2);
38. 38
39. 39      printf("bs1.length(): %d\r\n", bs1.length());
40. 40      printf("bs2.length(): %d\r\n", bs2.length());
41. 41函数printf
42. 42      return 0;
43. 43 }
输出结果:
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