string的size()和length()

标签: string算法语言c





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






      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()方法返回的是字节数,不管是否有汉字。