標籤:就會 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++ 字串