string比char[]更耗时,而string能完成的操作,char[]都可以实现。

求长度

//char[]
char ch1[] = "Hello ";
int n = strlen(ch1);  //不包括'\0'
cout << n << endl;  //输出6

//string
string str1 = "Hello ";
int n = str1.size();
int m = str1.lenth();
int k = strlen(str1.c_str()); 
cout << m << " " << n << " " << k << endl;  //输出 6 6 6

赋值

//char[]
char ch1[] = "Hello";
char ch2[] = "world";
strcpy(ch1, ch2);
cout << ch1 <<endl;  //输出"world"

//string
string str1 = "Hello";
string str2 = "world";
str1 = str2;  //或者str1.assign(str2, 0, 5)
cout << str1 << endl;  //输出"world"

合并

//char[]
char ch1[15] = "Hello ";
char ch2[] = "world";
strcat(ch1, ch2);
cout << ch1 << endl;  //输出"Hello world"
strncat(ch1, ch2, 3); //把ch2的前三个字符合并到ch1中
cout << ch1 << endl;  //输出"Hello worldwor" 

//string
string str1 = "Hello ";
string str2 = "world";
str1 += str2;
cout << str1 << endl;  //输出"Hello world"
str1.append(str2, 0, 5);  //合并从str2的下标0处,往后5个字符
cout << str1 << endl;  //输出"Hello worldworld" 

替换

//char[]
char ch1[15] = "Hello ";
char ch2[] = "world";
strncpy(ch1, ch2, 3);  //把ch2从首位开始后三位拿来替换ch1
cout << ch1 << endl;  //输出"worlo"

//string
string str1 = "Hello ";
string str2 = "world";
str1.replace(0, 2, str2, 2, 3);  //把str2下标2开始后三位字符替换str1下标0开始后两位字符
cout << str1 << endl;  //输出"rldllo" 

拷贝

//char[]
char ch1[15] = "Hello ";
char ch2[] = "world";
memmove(ch1, ch2, 2);  //把ch2首位起后两个字符赋给ch1
cout << ch1 << endl;  //输出"wollo"

//string
string str1 = "Hello ";
char ch2[] = "world";
str.copy(ch2, 2, 0)  //只能把string复制给char[],从str1下表0开始的2个字符赋给ch2
cout << ch2 << endl;  //输出"Herld"