c++ 字串

來源:互聯網
上載者:User

標籤:就會   c++11   use   memset   一個   int   模板   拼接字串   stdio.h   

#include<stdio.h>#include <stdlib.h>#include <string.h>#include<iostream>#include <string>//模板類型using std::string;using std::endl;using std::cout;void test0(void){//棧空間    char str1[] = "hello,world";    char str2[] = "shengzhen";    int len1 = sizeof(str1);    int len2 = sizeof(str2);    cout << "len1 = " << len1 << " , len2 = " << len2 << endl;//    strcat(str1, str2);//第一個參數代表的數組空間一定要是足夠的,否則在拼接字串之後就會越界    printf("%s\n", str1);    printf("%s\n", str2);    printf("%p\n", str1);    printf("%p\n", str2);}void test1(void){//堆空間    char *str1 = "hello,world";    char *str2 = "shengzhen";    int len = strlen(str1) + strlen(str2);    char *ptr = (char *)malloc( len + 1);    memset(ptr,0,len);    int len1 = sizeof(str1);    int len2 = sizeof(str2);    cout << "len1 = " << len1 << " , len2 = " << len2 << endl;    strcpy(ptr, str1);    strcat(ptr, str2);//第一個參數代表的數組空間一定要是足夠的,在拼接字串之後不能越界    char * p1 = strstr(str1, "world");         char * p2 = (char *)malloc(strlen(p1) + 1);    strcpy(p2, p1);    printf("%s\n", p2);    printf("%s\n", ptr);    printf("%p\n", ptr);    printf("%s\n", str1);    printf("%s\n", str2);    printf("%p\n", str1);    printf("%p\n", str2);    free(p2);    free(ptr);}void test2(){//c++ string 是一個類型    string s1 = "hello,world";    string s2 = "shengzhen";    string s3 = s1 + s2;    //可以把string看做一個數組來使用    for (int idx = 0; idx < s1.size(); ++idx)    {        cout << s1[idx] <<" ; "<<idx << endl;    }    size_t pos = s1.find("world");//從頭向尾尋找    string sub = s1.substr(pos, 5);    //迭代器    string::iterator it = s1.begin();    for (; it != s1.end(); ++it)    {        cout << *it << endl;    }//    c++11    for (auto & elem : s2)    {//auto關鍵字可以進行類型的自動推到        cout << elem << endl;    }    cout << "sub = " << sub<< endl;    cout << "s1 = " << s1 << endl;    cout << "s2 = " << s2 << endl;    s3.append(" wangdao");    cout << "s3 = " << s3 << endl;    string s4= s1 + s2 + "lihui" + s3;    cout << "s4 = "<<s4 << endl;}int main(void){    test2();    system("pause");    return 0;}

 

c++ 字串

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.