求字符串长度

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.使用std::string::size()获取字符串长度
basic_string同样具有获取大小的函数:
 
  1. size_type length( ) const;  
  2. size_type size( ) const
length()和size()的功能完全一样,它们仅仅返回 字符而非字节的个 数。如果遇到MCBS,它的表现和CStringA::GetLength()一样。


#include "stdafx.h"
#include <iostream>
#include <string>

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;
}



  • 8
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值