string的size()和length()

string的size()和length()
标签: string算法语言c
42303人阅读 评论(8) 收藏 举报
本文章已收录于:
分类:

      C++标准库中的string中两者的源代码如下:    
  size_type   __CLR_OR_THIS_CALL   length()   const  
  { //   return   length   of   sequence  
  return   (_Mysize);  
  }  
   
  size_type   __CLR_OR_THIS_CALL   size()   const  
  { //   return   length   of   sequence  
  return   (_Mysize);  
  }  
       所以两者没有区别。

 

       length是因为沿用C语言的习惯而保留下来的,string类最初只有length,引入STL之后,为了兼容又加入了size,它是作为STL容器的属性存在的,便于符合STL的接口规则,以便用于STL的算法。

       string类的size()/length()方法返回的是字节数,不管是否有汉字。

0
0
 
 
// sample2.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char* argv[])
{
 //h) + //串联字符串
    string hello("Hello ");
    string world("World!");
 cout<<hello<<world<<endl;
    cout<<"======== ======== ========="<<endl;
    //i) ==,!=,<,<=,>,>=,compare() //比较字符串
 {
  string abc("abc");  
  string abd("abd");
  cout<<abc.compare(abd)<<endl;
  string abb("abb");
        cout<<abc.compare(abb)<<endl;
        string abc2("abc");
  cout<<abc.compare(abc2)<<endl;
        cout<<"======== ======== ========="<<endl;
 }
 //j) size(),length() //返回字符数量
 {
  string abc("abc"); 
  cout<<sizeof(abc)<<endl;
  cout<<abc.size()<<endl;
  cout<<abc.length()<<endl;
        cout<<"======== ======== ========="<<endl;
 }
 return 0;
}


Hello World!
======== ======== =========
-1
1
0
======== ======== =========
16
3
3
======== ======== =========
Press any key to continue





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值