日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

C++获取字符串长度详解

發(fā)布時間:2024/4/18 c/c++ 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C++获取字符串长度详解 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

String 類型對象包括三種求解字符串長度的函數(shù):size() 和 length()、 maxsize()?和 capacity():

  • size() 和 length():這兩個函數(shù)會返回 string 類型對象中的字符個數(shù),且它們的執(zhí)行效果相同。
  • max_size():max_size() 函數(shù)返回 string 類型對象最多包含的字符數(shù)。一旦程序使用長度超過 max_size() 的 string 操作,編譯器會拋出 length_error 異常。
  • capacity():該函數(shù)返回在重新分配內(nèi)存之前,string 類型對象所能包含的最大字符數(shù)。

string 類型對象還包括一個 reserve() 函數(shù)。調(diào)用該函數(shù)可以為 string 類型對象重新分配內(nèi)存。重新分配的大小由其參數(shù)決定。reserve() 的默認參數(shù)為 0。

上述幾個函數(shù)的使用方法如下程序所示:

  • #include <iostream>
  • #include <string>
  • using namespace std;
  • int main ()
  • {
  • ??? int size = 0;
  • ??? int length = 0;
  • ??? unsigned long maxsize = 0;
  • ??? int capacity=0;
  • ??? string str ("12345678");
  • ??? string str_custom;
  • ??? str_custom = str;
  • ??? str_custom.resize (5);
  • ??? size = str_custom.size();
  • ??? length = str_custom.length();
  • ??? maxsize = str_custom.max_size();
  • ??? capacity = str_custom.capacity();
  • ??? cout << "size = " << size << endl;
  • ??? cout << "length = " << length << endl;
  • ??? cout << "maxsize = " << maxsize << endl;
  • ??? cout << "capacity = " << capacity << endl;
  • ??? return 0;
  • }
  • 程序執(zhí)行結(jié)果為:

    size = 8
    length = 8
    maxsize = 2147483647
    capacity = 15

    由此程序可知,string 類型對象 str_custom 調(diào)用 reserve() 函數(shù)時,似乎并沒有起到重新分配內(nèi)存的目的(筆者所用編譯器為 Visual C++6.0)。

    修改上述代碼,刪除語句 str_custom.reserve (5),在代碼 str_custom = str 之后如下添加代碼:

    str_custom.resize (5);

    修改后程序的執(zhí)行結(jié)構(gòu)如下:

    size = 5
    length = 5
    maxsize = 2147483647
    capacity = 15

    重新設(shè)置 string 類型對象 str_custom 的大小之后,重新求解 str_custom 的大小,其執(zhí)行效果與設(shè)置的數(shù)值一致(均為 5)。

    總結(jié)

    以上是生活随笔為你收集整理的C++获取字符串长度详解的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。