#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;
}