您的位置:首页 > 其它

string的size()和length()

2009-11-16 10:42 323 查看
string的size()和length()

标签:
string算法语言c

2009-11-16 10:42
42303人阅读 评论(8)
收藏
举报

本文章已收录于:


分类:
C++(36)




作者同类文章X

版权声明:本文为博主原创文章,未经博主允许不得转载。

      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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: