文字列の長さを求める

3641 ワード

1.sizeofを使用して文字列の長さを取得
sizeofの意味は明確で、それは取得するために使用されます.
文字配列のバイト数(もちろん終了文字0も含む).ANSI文字列とUNICOD文字列の場合、形式は次のとおりです.
 
  
  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.使用std::string::size()获取字符串长度
basic_string同样具有获取大小的函数:
 
  
  1. size_type length( ) const;  
  2. size_type size( ) const
length()和size()的功能完全一样,它们仅仅返回 字符而非字节的个 数。如果遇到MCBS,它的表现和CStringA::GetLength()一样。


#include "stdafx.h"
#include 
#include 

using namespace std;

int main()
{
	char str[] = "abcde";
	//sizeof()     
	cout << sizeof(str) << endl;
	cout << strlen(str) << endl;

	char *str1 = "abcde";
	//sizeof()    ,         
        //strlen()          
        cout << sizeof(str1) << endl;
	cout << strlen(str1) << endl;

	string str2 = "abcde";
	cout << str2.size() << endl;
	cout << str2.length() << endl;
	getchar();
	return 0;
}