string和字符数组的比较

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"
全部评论

相关推荐

努力的小明a:项目看着很眼熟,施磊老师吧,我也学的这个😋我当时是把rpc框架做成了一个分布式网盘,这是一个项目,然后muduo库做成集群即时通讯,又用QT做了个交互的客户端,这样又一个项目,然后一个轻量redis,一个CAD,总共四个项目,投了三个月就今天2月份一个小厂Qt offer,然后后面想开了,Qt啥的都能干,这个月get了个北京大厂的offer,做java后端,人生就是这么魔幻,现在就在去北京入职的路上
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务